2013-05-13 120 views
0

我有一個字符串看起來像:尋找模式和SQL Server 2008替換

set @s1 = '#12 + #13 - #14 * 3' 

我怎樣才能找到字符串的所有#XXX部件,更換它,這樣,最後一個字符串的樣子:

hashf('12') + hashf('13') - hash('14') * 3 

我試過用光標,但我花了太多時間和性能的原因,我不想使用它們。

我也試過regex。該模式是"#\d+"但我怎麼能適用於我的情況?

+1

永遠記住[正則表達式:現在你有兩個問題(http://www.codinghorror.com/blog/2008/06/regular-expressions-now -you-have-two-problems.html)以及有人[試圖用它們瘋狂](http://stackoverflow.com/a/1732454/1297603) – Yaroslav 2013-05-13 14:06:15

回答

0

我想出瞭解決方案:

DECLARE @s1 VARCHAR(max) 
DECLARE @length INT 
DECLARE @current INT 

SET @s1 = '#12 + #13 - #14 * 3' 
SET @length = Len(@s1) 
SET @current = 0 

DECLARE @returned_value VARCHAR(max) 

WHILE (@current < @length) 
    BEGIN 
     SET @current = Charindex('#', @s1, @current) 
     SET @s1 = Stuff(@s1, Charindex('#', @s1, @current) , 1, 'func1(''') 
     SET @s1 = Stuff(@s1, Charindex(' ', @s1, @current) , 1, ''') ') 
     SET @length = Len(@s1) 
     SET @current = Charindex('#', @s1, @current) 

     IF @current = 0 
     BEGIN 
      SET @current = @length 
     END 
    END 
SELECT @s1