【问题标题】:How to extract phone number from varchar column in SQL Server?如何从 SQL Server 的 varchar 列中提取电话号码?
【发布时间】:2018-01-03 10:46:27
【问题描述】:

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

例子:

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

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

谢谢

【问题讨论】:

  • 如果您只想要数字,此链接具有使用模式匹配的有用功能。 stackoverflow.com/questions/16667251/…
  • 哎呀....该链接上接受的答案是使用循环。这可以基于集合来完成。我会尽快发布答案。
  • 看起来 scsimon 打败了我。我打算做类似的事情。
  • @SeanLange 这可能是我最后一次打败你了——你大部分时间都快坏了
  • 如果有两个电话号码怎么办?您可能需要支持多少种不同的国际格式?这可以决定您需要进行哪种解析,以及如何呈现不具有您可能期望的确切位数的数字。为您认为可能是电话号码的内容解析文本块可能会变得很麻烦。

标签: sql sql-server


【解决方案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

【讨论】:

  • 如果电话号码碰巧用空格分隔,则会中断。
  • 不用担心@Abhijith,但有一点建议......我会尝试规范化您的数据并将此输入字段保持为严格的数字以防止这种情况发生。
【解决方案2】:

也可以使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 2016-07-02
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 2014-05-16
    相关资源
    最近更新 更多