在标量函数SQL Server 2012中使用if语句

时间:2014-11-07 20:03:04

标签: tsql sql-server-2012

尝试返回10位数的电话号码 - 我认为我删除了各种非数字字符 - 我需要帮助的是删除'1'  来自那些电话号码为“1(xxx)xxx-xxxx”格式的案例。

IF OBJECT_ID (N'dbo.CleanPhone',N'FN') IS NOT NULL
DROP FUNCTION dbo.CleanPhone
GO

CREATE FUNCTION dbo.CleanPhone (@PhoneNumber varchar(200))
RETURNS varchar(10)
AS

BEGIN

DECLARE @CleanPhone varchar(200);

SET @CleanPhone =  replace(replace(replace(replace(replace(ltrim(rtrim(@PhoneNumber)),'-',''),' ',''),'(',''),')',''),'.','')

--being mysudo code 
IF LEN @CleanPhone > 10 AND Left(@CleanPhone,2) = '1 ' THEN Right(CleanPhone,10)
ELSE @CleanPhone
--end my sudo code 
RETURN @CleanPhone 
END;
GO

2 个答案:

答案 0 :(得分:1)

由于您的PhoneNumber具有以下格式:' 1(xxx)xxx-xxxx'

你可以选择

SET @CleanPhone =  replace(replace(replace(replace(replace(ltrim(rtrim(@PhoneNumber)),'-',''),' ',''),'(',''),')',''),'.','')

将上述声明替换为

SET @CleanPhone =  right(<all your replace goes here>,10)   
RETURN @CleanPhone

答案 1 :(得分:0)

我建议使用case语句来处理不同的条件,这是一个易于代码维护的建议和可读性。

SET @CleanPhone = CASE WHEN条件1那么结果                        当条件2然后结果2                        ELSE defaullVal                   END