2

How to replace only 2 with 1 from string (12 | 2) & 23 | 4 & 25 | (6 | 7). but don't want to replace 2 which are within 12,23,25..

Because i don't know, how many 2 are in string. So i only want to replace 2.

I tried with replace clause but it replaces all 2.

So problem arising while replacing only 2.

4

2 回答 2

5

我很久以前回答了一个可能有帮助的问题: 如何从 SQL Server 中的字符串中去除所有非字母字符?

在那个问题中,我展示了一个在这里也很有帮助的代码块(当然还有修改)。

 Declare @Temp VarChar(100)
 Set @Temp = '(12 | 2) & 23 | 4 & 25 | (6 | 7)'

 Declare @FindCharacter VarChar(10),
        @ReplaceCharacter VarChar(10)

Set @FindCharacter = '2'
Set @ReplaceCharacter = '1'

 While PATINDEX('%[^0-9]' + @FindCharacter + '[^0-9]%', @Temp) > 0
    Set @Temp = Stuff(@Temp, PATINDEX('%[^0-9]' + @FindCharacter + '[^0-9]%', @Temp) + 1, Len(@FindCharacter), @ReplaceCharacter)

Select @Temp

基本上,此代码搜索 {not a number}{value 2}{not a number}。这也意味着如果 2 是字符串的第一个或最后一个字符,则代码不会替换它。这里的“替换”实际上是通过 STUFF 函数完成的。由于 STUFF 一次只能替换一个字符串,因此您需要一个 while 循环来使其多次替换。

这是一个用于替换的标量 UDF。即使它们位于搜索字符串的开头或结尾,它也会容纳替换。

Create Function dbo.ReplaceNumber(@Input VarChar(100), @Find VarChar(10), @Replace VarChar(10))
Returns VarChar(100)
AS
Begin

    Set @Input = '~' + @Input + '~'

    While PATINDEX('%[^0-9]' + @Find + '[^0-9]%', @Input) > 0
        Set @Input = Stuff(@Input, PATINDEX('%[^0-9]' + @Find + '[^0-9]%', @Input) + 1, Len(@Find), @Replace)

    Return SubString(@Input, 2, Len(@Input)-2)
End

您可以像这样测试/使用该功能:

Select dbo.ReplaceNumber('(12 | 2) & 23 | 4 & 25 | (6 | 7)','2','1')
Select dbo.ReplaceNumber('2 & 23','2','1')
Select dbo.ReplaceNumber('2 & 23','23','10')
于 2013-11-07T14:33:35.897 回答
1

以下示例比较递归 CTE 的每一步的前一个值、当前值和下一个值

DECLARE @text nvarchar(max) = '(12 | 2) & 23 | 4 & 25 | (6 | 7)',
        @Search nvarchar(1) = '2',
        @Repl nvarchar(1) = '1'
;WITH cte AS
  (SELECT 1 AS Number, CASE WHEN SUBSTRING (@text, 1, 1) = @Search
                            THEN @Repl ELSE SUBSTRING (@text, 1, 1) END AS Num
   UNION ALL
   SELECT c.Number + 1,
      c.Num + CASE WHEN SUBSTRING (@text, c.Number + 1, 1) = @Search
                    AND ISNUMERIC(SUBSTRING(@text, c.Number, 1)) = 0
                    AND ISNUMERIC(SUBSTRING(@text, c.Number + 2, 1)) = 0
                       THEN @Repl ELSE SUBSTRING (@text, c. Number + 1, 1) END
   FROM cte c
   WHERE Number < LEN(@text)
   )
   SELECT TOP 1 Num
   FROM cte
   ORDER BY Number DESC

演示SQLFiddle

于 2013-11-07T16:14:11.113 回答