SQL Server 2000: how do I return only the number from a phone number column

∥☆過路亽.° 提交于 2019-12-01 20:24:46

问题


I'm trying to strip out the "(", ")", "-", "x" or "X" "ext" and spaces from each phone number so I am left with only the first 10 digits or 1st 10 numbers of a phone number.

Is there a simple way to allow only the first 10 digits to pass through in sql 2000. I was thinking about using replace but it requires a replace for each character or group of characters and is not very neat. Is there a way with a standard install of sql2000 to return only the first 10 numbers.

Examples before and after

Before                      After
(555) 555-5555 ext55555     5555555555
340 555-5555                3405555555

回答1:


I think your only option is to create a UDF that does it. If you were using 2005+ you could create a CLR function to do it.

UDF:

create function dbo.RemoveNonNumericChar(@str varchar(500))  
returns varchar(500)  
begin  
declare @startingIndex int  
set @startingIndex=-1 
while @startingIndex <> 0 
begin  
    set @startingIndex= patindex('%[^0-9]%',@str)  
    if @startingIndex <> 0  
    begin  
        set @str = replace(@str,substring(@str,@startingIndex,1),'')  
    end   
end  
return @str  
end

go  

select dbo.RemoveNonNumericChar('(555) 555-5555 ext55555')  



回答2:


See if this works:

Declare @Expression varchar(15)
Declare @MyVariable varchar(20)

Set @Expression = '%[^0-9]%' 
Set @MyVariable = '(555) 555-5555 ext55555'

While PatIndex(@Expression, @MyVariable) > 0
   Set @MyVariable = Stuff(@MyVariable, PatIndex(@Expression, @MyVariable), 1, '')

Print @MyVariable

555555555555




回答3:


Another way to do it, if you didn't want to use a User Defined Function would be to use the REPLACE function, like so:

SELECT Phone, REPLACE(REPLACE(REPLACE(REPLACE(Phone,' ',''),'(',''),')',''),'-','') AS NewPhone
FROM Contacts

Although its a bit klunky, it should serve your purpose.



来源:https://stackoverflow.com/questions/6378441/sql-server-2000-how-do-i-return-only-the-number-from-a-phone-number-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!