从变量中提取特定的字符串

时间:2018-10-29 05:47:46

标签: sql-server

我有一个包含动态字符串的变量。我只想得到等于COATitle的单词。

DECLARE @String Varchar(250)
 SET @String = 'COATitle = ''Hello'' AND Date = ''2018-10-09'' AND Name = ''Warner Bros'''

 SELECT @String AS String

此字符串是从前端提供的,因此用户也可以按不同的顺序输入。例如

SET @String = 'Date = ''2018-10-09'' AND COATitle = ''Hello Tonia'' AND Name = ''Warner Bros'''
SET @String = 'COATitle = ''Hello'' AND Name = ''Warner Bros'' Date = ''2018-10-09'' AND '
SET @String = 'COATitle = ''Hello World'' AND Date = ''2018-10-09'' AND Name = ''Warner Bros'''
SET @String = 'COATitle = ''Piece of Cake'' AND Date = ''2018-10-09'' AND Name = ''Tim Martin'''

上述字符串的预期输出为:

1: Hello Tonia
2: Hello
3: Hello World
4: Piece of Cake

1 个答案:

答案 0 :(得分:1)

这里的一种方法是只在SQL Server中使用基本字符串函数。我们可以使用输入的子字符串作为输入,使用起始点作为紧跟COATitle = '之后的文本,一直持续到紧接下一个单引号之前。

SELECT
    word,
    SUBSTRING(word,
              CHARINDEX('COATitle = ''', word) + 12,
              CHARINDEX('''', word, CHARINDEX('COATitle = ''', word) + 12) -
                  CHARINDEX('COATitle = ''', word) - 12) AS target
FROM yourTable;

enter image description here

Demo