我要求在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
答案 0 :(得分:2)
尝试这种方式:
DECLARE @Number VARCHAR(64)
SET @Number = '123456789'
select '**'+substring(@Number,3,len(@Number)-4)+'**'
答案 1 :(得分:2)
您可以尝试STUFF
功能
SET @Number = STUFF(STUFF(@Number,1,2,'**'),LEN(@Number)-1,2,'**')
<强> SQLFiddle DEMO 强>