2014-09-04 81 views
1

我有一个SQL变量:如何在SQL Server中的特定字符之前和之后替换子字符串?

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?

+0

这里的依赖是什么?什么使得该字符串与其余字符串区分开来。括号是文字吗?因为在你的情况下,实际上会有括号吗? – 2014-09-04 16:44:56

+1

是的,括号可以区分子字符串 – sns 2014-09-04 16:56:23

回答

1

之前采取“[”添加和更换的子字符串右“]”

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) 
+0

谢谢。这正是我想要的:) – sns 2014-09-04 16:57:54

1

难道仅仅是这样简单的子串?

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 “有必要或不...但它只是一个普通的一种调整的我见过,在字符串长度计算)


注意重新”回答&编辑:
- 我的回答娃。写成好像'this is test string '等字符串为确认
- Patindex(替换Charindex)意味着只有后缀字符串也存在时才能识别前缀字符串。
- 我将[添加到之前的字符串中,并将]添加到后面的字符串(根据您稍后的评论发布),这听起来像括号实际上是要识别的字符串的一部分。
- [本身是封闭的,在[],以“逃避”它 - 所以它将被字面解释。

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);