2013-05-13 67 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