我需要格式化数据库中保存的现有电话号码。首先,我需要用字符清除电话号码。
801-113-1521
801.456.7891
1213-345-6789 ext 219
(323)567=2251
应为:
8011131521
8014567891
12133456789
3235672251
之后,我将其格式化为(3位区号)###-#### 然后忽略11位数字的国家代码“ 1”
我尝试过
DECLARE @string varchar(100)
SET @string = phoneNumber
-- loop till there are characters left in a string
WHILE PATINDEX('%[^0-9]%',@string) <> 0
BEGIN
-- replace characters with empty space
SET @string = STUFF(@string,PATINDEX('%[^0-9]%',@string),1,'')
END
SELECT @string
但是当涉及到1213-345-6789 ext 219时,它包括219。我是mssql的新手。
答案 0 :(得分:1)
只需使用嵌套的replace
:
select replace('.', '',
replace('=', '',
replace(')', '',
replace('(', '',
replace(',', '',
phoneNumber)))))
from MyTable
答案 1 :(得分:1)
ALTER FUNCTION [dbo].[GetPhone]
(@strAlphaNumeric VARCHAR(256))
RETURNS NVARCHAR(10)
AS
BEGIN
DECLARE @SourceStr NVARCHAR(10);
DECLARE @intAlpha INT
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
BEGIN
WHILE @intAlpha > 0
BEGIN
SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
END
END
if(LEFT(@strAlphaNumeric,1)='1') begin
SET @SourceStr =RIGHT(CONVERT(NVARCHAR(11), @strAlphaNumeric),10);
end else begin
SET @SourceStr =CONVERT(NVARCHAR(10), @strAlphaNumeric);
end
RETURN @SourceStr;
END
答案 2 :(得分:1)
您可以尝试再创建一个函数来清除字母后面的任何尾随数字。
首先,清理所有特殊字符。 其次,清理结尾的数字和字母。
CREATE Function [dbo].[RemoveSpecialCharacters](@Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin
Declare @KeepValues as varchar(50)
Set @KeepValues = '%[^0-9A-Za-z]%'
While PatIndex(@KeepValues, @Temp) > 0
Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')
Return @Temp
End
CREATE Function [dbo].[RemoveExtraCharacters](@Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin
Declare @KeepValues as varchar(50)
Set @KeepValues = '%[^0-9]%'
While PatIndex(@KeepValues, @Temp) > 0
-- Here you specify the length of text that you need to remove len(@Temp)-PatIndex(@KeepValues, @Temp)+1
Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), len(@Temp)-PatIndex(@KeepValues, @Temp)+1, '')
Return @Temp
End
然后您可以在列上调用函数。
SELECT [dbo].[RemoveExtraCharacters]([dbo].[RemoveSpecialCharacters](PhoneNo)) FROM Yourtable
编辑:
这将删除国家/地区代码。
SELECT CASE WHEN
LEN([dbo].[RemoveExtraCharacters]([dbo].[RemoveSpecialCharacters](PhoneNo)))>10 THEN
RIGHT([dbo].[RemoveExtraCharacters]([dbo].[RemoveSpecialCharacters](PhoneNo)), 10)
ELSE
[dbo].[RemoveExtraCharacters]([dbo].[RemoveSpecialCharacters](PhoneNo))
END AS PhoneNo
FROM Yourtable
您可以看到示例here