SQL - Query Phonenumber that are stored inconsistently

后端 未结 6 1064
既然无缘
既然无缘 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 08:06

    In Oracle:

    SELECT  *
    FROM    mytable
    WHERE   REGEXP_REPLACE(Phonenumber, '[^0-9]', '') = '5551234567'
    

    In SQL Server 2005+:

    WITH    digits AS
            (
            SELECT  1 AS digit
            UNION ALL
            SELECT  digit + 1
            FROM    digits
            WHERE   digit <= 100
            )
    SELECT  *
    FROM    mytable
    WHERE   (
            SELECT  SUBSTRING(number, digit, 1) AS [text()]
            FROM    digits
            WHERE   SUBSTRING(number, digit, 1) BETWEEN '0' AND '9'
            FOR XML PATH('')
            ) = '5551234567'
    

    , or, if you want to see the normalized phone value,

    WITH    digits AS
            (
            SELECT  1 AS digit
            UNION ALL
            SELECT  digit + 1
            FROM    digits
            WHERE   digit <= 100
            ),
            phones AS
            (
            SELECT  m.*,
                    (
                    SELECT  SUBSTRING(number, digit, 1) AS [text()]
                    FROM    digits
                    WHERE   SUBSTRING(number, digit, 1) BETWEEN '0' AND '9'
                    FOR XML PATH('')
                    ) AS nphone
            FROM    mytable m
            )
    SELECT  *
    FROM    phones
    WHERE   nphone = '5551234567'
    

    However, you better create another column for normalized phone values, fill it in a trigger and index it, so you can query more efficiently.

提交回复
热议问题