we a phonenumber field in our database and I would like to do a simple lookup query like:
SELECT * FROM TABLE WHERE Phonenumber = \'555123456\'
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.