SELECT with a Replace()

前端 未结 8 1021
执念已碎
执念已碎 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%'
    
    0 讨论(0)
  • 2021-01-31 09:39
    SELECT *
    FROM Contacts
    WHERE ContactId IN
        (SELECT a.ContactID
        FROM
            (SELECT ContactId, Replace(Postcode, ' ', '') AS P
            FROM Contacts
            WHERE Postcode LIKE '%N%W%1%0%1%') a
        WHERE a.P LIKE 'NW101%')
    
    0 讨论(0)
提交回复
热议问题