简体   繁体   中英

Validate phone number using SQL

I need to check if phone number is in below format or not

+1(111)111-1111
(111)111-1111
1111111111

I am using this logic but not getting what I want

DECLARE @Customers TABLE (PhoneNumber VARCHAR(20))
INSERT @Customers
VALUES
    ('+1(111)111-1111'),
    ('1111111111'),
    ('11(11)111111'),
    ('11abcd1111'),
    (')123(45678-9-0-'),
    ('(111)111-1111')

SELECT PhoneNumber
FROM @Customers
WHERE PhoneNumber NOT LIKE '%[^0-9()-]%'
--AND REPLACE(REPLACE(REPLACE(PhoneNumber, '(', ''), ')', ''), '-', '') LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
AND LEN(REPLACE(REPLACE(REPLACE(REPLACE(PhoneNumber, '(', ''), ')', ''), '-', ''),'+','')) = 10 -- Alternate test

The result I am getting

1111111111
11(11)111111
)123(45678-9-0-

UPDATE : +1(111)111-1111 should also be in the result list l but it is not. How can I add it?

SELECT PhoneNumber
FROM @Customers
WHERE PhoneNumber LIKE replace('+1(111)111-1111%','1','[0-9]')
   OR PhoneNumber LIKE replace('(111)111-1111%','1','[0-9]')
   OR PhoneNumber LIKE replace('1111111111%','1','[0-9]')

My query :

DECLARE @Customers TABLE (PhoneNumber VARCHAR(20))
INSERT @Customers
VALUES
    ('+1(111)11-1111'),
    ('2222222222'),
    ('11(11)111111'),
    ('11'),
    (')123(45678-9-0-'),
    ('(111)111-1111')

SELECT PhoneNumber
FROM @Customers
WHERE 
      PhoneNumber  LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
      or PhoneNumber LIKE '[+][0-9][(][0-9][0-9][0-9][)][0-9][0-9][-][0-9][0-9][0-9][0-9]'
      or PhoneNumber LIKE '[(][0-9][0-9][0-9][)][0-9][0-9][0-9][-][0-9][0-9][0-9][0-9]'

Output:

PhoneNumber
+1(111)11-1111
2222222222
(111)111-1111

Let me know if you want to replace the bracket or +/- sign.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM