【问题标题】:How to replace a substring before and after a specific character in SQL Server?如何替换 SQL Server 中特定字符前后的子字符串?
【发布时间】:2014-10-29 12:26:50
【问题描述】:

我有一个 SQL 变量:

SET @TSQL = 'this is test string [this text may vary] other text'

现在我想用我自己的不同文本替换子字符串“[此文本可能有所不同]”。 有谁能够帮我?请记住,我要替换的子字符串不是静态的,而是动态的,可能会有所不同。

这看起来与我的问题相似,但仅适用于特定字符之前。我需要前后两个字符。

How do I replace a substring of a string before a specific character?.

【问题讨论】:

  • 这里的依赖是什么?是什么使该子字符串与字符串的其余部分区分开来。括号是字面意思吗?如在您的情况下实际上会有括号吗?
  • 是的,括号可以区分子字符串

标签: sql sql-server database


【解决方案1】:

STUFF 做得很好。

declare @string         [nvarchar](max) = N'This is a boilerplate string where [this text may vary] but this text should stay'
    , @replace_me   [nvarchar](max) = N'[this text may vary]'
    , @replace_with [nvarchar](max) = N'cool new stuff!';
select stuff (@string
          , charindex(@replace_me
                     , @string)
          , len(@replace_me)
          , @replace_with); 

【讨论】:

    【解决方案2】:

    就这么简单吗?

    SET @TSQL = 'this is test string ' + @NewText + ' other text'
    

    或者,如果预期的前置文本不是前面的唯一文本,则可能:

    SET @TSQL = 'this is test string [this text may vary] other text'
    DECLARE INT @TSQL_PrefixEnding = PATINDEX('%this is test string [[]%[]] other text%', @TSQL) + LEN('this is test string [') - 1
    DECLARE INT @TSQL_SuffixStart = CHARINDEX('] other text', @TSQL, @TSQL_PrefixEnding)
    SET @TSQL = LEFT(@TSQL, @TSQL_PrefixEnding ) + @NewText + SUBSTRING(@TSQL, @TSQL_SuffixStart, LEN(@TSQL) - @TSQL_SuffixStart + 1)
    

    (注意:我必须对其进行测试,看看是否需要“+1”...但这只是我见过的一种常见的调整,在字符串长度计算中。)


    Notes re' 回答和编辑:
    -- 我的回答好像'this is test string ' 等是recognize 的字符串。
    -- Patindex(替换 Charindex)意味着你只识别前缀字符串,当后缀字符串也存在时。
    -- 我在之前的字符串中添加了[,在之后的字符串中添加了](无论它们出现在哪里),这听起来像是括号实际上是要识别的字符串的一部分。
    -- [ 本身被包含在[] 中,以“转义”它——因此它将按字面意思解释。

    【讨论】:

      【解决方案3】:

      取'['之前的子字符串添加你的替换和']'的子字符串

      declare @TSQL varchar(100)
      declare @R varchar(100)
      SET @TSQL = 'this is test string [this text may vary] other text'
      SET @R = 'MySubstitute'
      Select Left(@TSQL,Charindex('[',@TSQL)-1) + @R + RIGHT(@TSQL,Charindex(']',REVERSE(@TSQL))-1)
      

      【讨论】:

      • 谢谢。这正是我想要的:)
      猜你喜欢
      • 1970-01-01
      • 2021-10-31
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      • 2019-10-20
      相关资源
      最近更新 更多