1

我需要在 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
4

2 回答 2

2

试试这个方法:

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

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

SQL 小提琴演示

于 2013-07-24T08:14:07.020 回答
2

你可以试试STUFF功能

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

SQLFiddle 演示

于 2013-07-24T08:15:22.463 回答