2013-07-24 154 views
1

我有一個要求與SQL星號(*),例如替換字符串的第一個和最後2個字符:最快方式

輸入 :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

試試這個方法:

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

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

SQL Fiddle Demo

2

您可以嘗試STUFF功能

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

SQLFiddle DEMO