sql-server – 如何在SQL中创建REPLACE PATTERN?

前端之家收集整理的这篇文章主要介绍了sql-server – 如何在SQL中创建REPLACE PATTERN?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个很长的NVARCHAR变量,我需要替换这样的模式:
DECLARE @data NVARCHAR(200) = 'Hello [PAT1] stackoverflow [PAT2] world [PAT3]'

我需要用空格替换所有[PAT%],如下所示:

'Hello stackoverflow world'

如何在sql Server 2008中使用T-sql执行此操作?

我正在寻找其他问题,我只找到了this,但它对我没有帮助,因为我不需要保留字符串的原始部分.

解决方法

您可以使用此功能进行图案替换.您可以使用此 SQL-Fiddle demo进行测试以进行测试.
CREATE FUNCTION dbo.PatternReplace
(
   @InputString VARCHAR(4000),@Pattern VARCHAR(100),@ReplaceText VARCHAR(4000)
)
RETURNS VARCHAR(4000)
AS
BEGIN
   DECLARE @Result VARCHAR(4000) SET @Result = ''
   -- First character in a match
   DECLARE @First INT
   -- Next character to start search on
   DECLARE @Next INT SET @Next = 1
   -- Length of the total string -- 8001 if @InputString is NULL
   DECLARE @Len INT SET @Len = COALESCE(LEN(@InputString),8001)
   -- End of a pattern
   DECLARE @EndPattern INT

   WHILE (@Next <= @Len) 
   BEGIN
      SET @First = PATINDEX('%' + @Pattern + '%',SUBSTRING(@InputString,@Next,@Len))
      IF COALESCE(@First,0) = 0 --no match - return
      BEGIN
         SET @Result = @Result + 
            CASE --return NULL,just like REPLACE,if inputs are NULL
               WHEN  @InputString IS NULL
                     OR @Pattern IS NULL
                     OR @ReplaceText IS NULL THEN NULL
               ELSE SUBSTRING(@InputString,@Len)
            END
         BREAK
      END
      ELSE
      BEGIN
         -- Concatenate characters before the match to the result
         SET @Result = @Result + SUBSTRING(@InputString,@First - 1)
         SET @Next = @Next + @First - 1

         SET @EndPattern = 1
         -- Find start of end pattern range
         WHILE PATINDEX(@Pattern,@EndPattern)) = 0
            SET @EndPattern = @EndPattern + 1
         -- Find end of pattern range
         WHILE PATINDEX(@Pattern,@EndPattern)) > 0
               AND @Len >= (@Next + @EndPattern - 1)
            SET @EndPattern = @EndPattern + 1

         --Either at the end of the pattern or @Next + @EndPattern = @Len
         SET @Result = @Result + @ReplaceText
         SET @Next = @Next + @EndPattern - 1
      END
   END
   RETURN(@Result)
END

Resource link.

原文链接:https://www.f2er.com/mssql/84101.html

猜你在找的MsSQL相关文章