SELECT with a Replace()

前端 未结 8 1012
执念已碎
执念已碎 2021-01-31 09:03

I have a table of names and addresses, which includes a postcode column. I want to strip the spaces from the postcodes and select any that match a particular pattern. I\'m tryin

8条回答
  •  隐瞒了意图╮
    2021-01-31 09:34

    if you want any hope of ever using an index, store the data in a consistent manner (with the spaces removed). Either just remove the spaces or add a persisted computed column, Then you can just select from that column and not have to add all the space removing overhead every time you run your query.

    add a PERSISTED computed column:

    ALTER TABLE Contacts ADD PostcodeSpaceFree AS Replace(Postcode, ' ', '') PERSISTED 
    go
    CREATE NONCLUSTERED INDEX IX_Contacts_PostcodeSpaceFree 
    ON Contacts (PostcodeSpaceFree) --INCLUDE (covered columns here!!)
    go
    

    to just fix the column by removing the spaces use:

    UPDATE Contacts
        SET Postcode=Replace(Postcode, ' ', '')
    

    now you can search like this, either select can use an index:

    --search the PERSISTED computed column
    SELECT 
        PostcodeSpaceFree 
        FROM Contacts
        WHERE PostcodeSpaceFree  LIKE 'NW101%'
    

    or

    --search the fixed (spaces removed column)
    SELECT 
        Postcode
        FROM Contacts
        WHERE PostcodeLIKE 'NW101%'
    

提交回复
热议问题