在T-SQL中从开始和结束替换一系列字符的最快方法

时间:2013-07-24 08:08:21

标签: sql tsql sql-server-2005

我要求在SQL中用星号(*)替换字符串的第一个和后两个字符,例如:

输入:123456

输出**34**

我就是这样做的,无论如何我可以改进下面的脚本吗?(缩短时间,调用内置函数以获得所需的输出等)

 DECLARE @Number VARCHAR(64)
SET @Number = '123456789'

IF(LEN(@Number) >= 5)
BEGIN

--Remove the first two characters
SET @Number = SUBSTRING(@Number,3,LEN(@Number))

--Remove the last two characters
SET @Number = SUBSTRING(@Number,0,LEN(@Number)- 1)

--Add two asterisks at front and end
SEt @Number = '**' + @Number + '**'

SELECT @Number
END

2 个答案:

答案 0 :(得分:2)

尝试这种方式:

DECLARE @Number VARCHAR(64)
SET @Number = '123456789'

select '**'+substring(@Number,3,len(@Number)-4)+'**'

SQL Fiddle Demo

答案 1 :(得分:2)

您可以尝试STUFF功能

SET @Number = STUFF(STUFF(@Number,1,2,'**'),LEN(@Number)-1,2,'**')

<强> SQLFiddle DEMO