简体   繁体   English

在SQL Server 2008中查找模式并进行替换

[英]Finding pattern and replacing in SQL Server 2008

I have strings that look like: 我有看起来像的字符串:

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

How can I find all the #XXX parts of the string and replace it so that the final string looks like: 如何找到字符串的所有#XXX部分并将其替换,以便最终的字符串如下所示:

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

I tried it using cursors but I took too much time and for performance reasons I don't want to use them. 我使用游标尝试了此操作,但是我花了太多时间,并且出于性能方面的考虑,我不想使用它们。

I tried also regex . 我也尝试过regex The pattern is "#\\d+" but how can I apply it in my case? 模式为"#\\d+"但如何在我的情况下应用?

I figured out the solution: 我想出了解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM