如何从SQL Server中的varchar列中提取电话号码?

时间:2017-07-27 15:38:12

标签: sql sql-server

我的表格中有一个varchar列,其中可以包含不同格式的电话号码以及其中的一些文字。

示例:

"This is a test 111-222-3344"  
"Some Sample Text (111)-222-3344"  
"Hello there 1112223344 . How are you?"

如何从中提取电话号码?我已经查找了其他解决方案(Another Post),但它们不符合我的要求。

谢谢

2 个答案:

答案 0 :(得分:1)

好吧,因为它们的格式不同,我会以相同的格式提取它们。

--Handles parentheses, commas, spaces, hyphens..
declare @table table (c varchar(256))
insert into @table
values
('This is a test 111-222-3344'),
('Some Sample Text (111)-222-3344'),
('Hello there 111222 3344 / How are you?'),
('Hello there 111 222 3344 ? How are you?'),
('Hello there 111 222 3344. How are you?')

select
replace(LEFT(SUBSTRING(replace(replace(replace(replace(replace(c,'(',''),')',''),'-',''),' ',''),',',''), PATINDEX('%[0-9.-]%', replace(replace(replace(replace(replace(c,'(',''),')',''),'-',''),' ',''),',','')), 8000),
           PATINDEX('%[^0-9.-]%', SUBSTRING(replace(replace(replace(replace(replace(c,'(',''),')',''),'-',''),' ',''),',',''), PATINDEX('%[0-9.-]%', replace(replace(replace(replace(replace(c,'(',''),')',''),'-',''),' ',''),',','')), 8000) + 'X') -1),'.','')
from @table

Partial Credit

答案 1 :(得分:0)

也可以使用Patindex,Reverse,Replace Functions

尝试这种方式
declare @Datatable table (c varchar(256))
insert into @Datatable
values
('This is a test 111-222-3344'),
('Some Sample Text (111)-222-3344'),
('Hello there 111222 3344 / How are you?'),
('Hello there 111 222 3344 ? How are you?'),
('Hello there 111 222 3344. How are you?')



 SELECT c AS VColumn,
REPLACE(REPLACE(REPLACE(REVERSE(SUBSTRING((c2),PATINDEX('%[0-9]%',(c2)),Len((c2)))),')',''),'-',''),' ','') AS ExtractedNUmber from
(
SELECT *,REVERSE(SUBSTRING(c,PATINDEX('%[0-9]%',c),LEN(c) )) AS C2 from @Datatable

)dt

结果

VColumn                                     ExtractedNUmber
--------------------------------------------------------------
This is a test 111-222-3344                 1112223344
Some Sample Text (111)-222-3344             1112223344
Hello there 111222 3344 / How are you?      1112223344
Hello there 111 222 3344 ? How are you?     1112223344
Hello there 111 222 3344. How are you?      1112223344