我的表格中有一个varchar
列,其中可以包含不同格式的电话号码以及其中的一些文字。
示例:
"This is a test 111-222-3344"
"Some Sample Text (111)-222-3344"
"Hello there 1112223344 . How are you?"
如何从中提取电话号码?我已经查找了其他解决方案(Another Post),但它们不符合我的要求。
谢谢
答案 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
答案 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