SQL - Query Phonenumber that are stored inconsistently

后端 未结 6 1065
既然无缘
既然无缘 2021-01-14 07:10

we a phonenumber field in our database and I would like to do a simple lookup query like:

SELECT * FROM TABLE WHERE Phonenumber = \'555123456\'
6条回答
  •  被撕碎了的回忆
    2021-01-14 07:51

    IF you can alter the table (assuming it's SQL Server 2005 and up), you could add a computed column to your table, and persist it. This column could hold a "cleaned up" representation of your "phonenumber" field.

    Something like this:

     create function dbo.CleanPhone(@phone varchar(100))
     returns varchar(100)
     with schemabinding
     as begin
       return
         replace(replace(replace(replace(replace(replace(@phone, ' ', ''), 
                 '-', ''), '(', ''), ')', ''), '-', ''), '+', '')
     end
    

    and then:

    alter table (yourtable)
     add cleanedPhone as dbo.CleanPhone(Phone) persisted
    

    Now, your "CleanedPhone" column would always contained a "cleaned up" version of your phone number - always something like: 555123456.

    Since it's a PERSISTED field, you don't incur a performance penalty when querying, either - the value is created and stored in your table, and is available as a normal column.

    On this, you could now query quite easily.

    Marc

提交回复
热议问题