2015-06-12 102 views
-1

我有一个SQL表格,其中电话号码为列。如何从SQL中的电话号码提取*区号*

(201) 411-5200x4002 
1 (5410) 651-8868 x 5 
1-308-987-5920 x8031 
2118477656 
2195992321x289 
313-877-5916 

我需要提取出Area Code这些电话号码。区号是前三位数字。但是,如果我们也有国家代码(1(5410)651-8868),那么它很难找到。

我正在使用SQL Server 2012 ...

请帮忙。

+0

你能告诉我们什么正确的结果是你给敬请6点的例子吗? –

回答

1

你可以创建一个功能,你可以通过你的手机号码,它会返回你的区号。

CREATE FUNCTION [dbo].[f_GetAreaCode] 
(
    @phoneNumber as nvarchar(200) 
) 
RETURNS nvarchar(50) 
AS 
BEGIN 
    -- Declare the return variable here 
    DECLARE @areaCodeAbbr as nvarchar(50) 

    -- Add the T-SQL statements to compute the return value here 
    if Exists(select 1 from sys.tables where @phoneNumber like '1-%' or @phoneNumber like '1(%') or @phoneNumber like '1 %') 
     set @phoneNumber = RIGHT(@phoneNumber,len(@phoneNumber)-2) 

    set @phoneNumber = replace(@phoneNumber,'(','') 
    set @phoneNumber = replace(@phoneNumber,')','') 
    set @phoneNumber = replace(@phoneNumber,'-','') 
    set @phoneNumber = LTRIM(@phoneNumber) 

    SELECT 
     @areaCodeAbbr = left(@phoneNumber,3) 

    -- Return the result of the function 
    RETURN @areaCodeAbbr 

END 

调用的函数写像SQL -

Select dbo.f_GetAreaCode('(201) 411-5200x4002') 
+1

请指定这是哪个dbms! (看起来不像ANSI SQL,也没有指定问题...) – jarlh

+0

我正在使用SQL Server 2012 .. –

+1

这对'1(5410)651-8868 x 5'不起作用,您应该添加这行也是:'set @phoneNumber = replace(@phoneNumber,'','')'替换空格。 –