我不明白如何有条件地更改SUBSTRING(..)
我在sql表中有一个文本字段,我想从
中检索一个子字符串文本的特定部分我在检索子字符串时遇到问题,因为我无法保证下一个字符串。
例如,我有:
... Tracking Code : /a/delimited/string AttributeW : ValueW ...
和
... Tracking Code : /a/different/delimited/string A random string ...
我想分别/a/delimited/string
和/a/different/delimited/string
我当前的sql看起来像:
DECLARE @TrackingStartStr VARCHAR(50), @TrackingEndStr VARCHAR(50)
SET @TrackingStartStr = 'Tracking Code :'
SET @TrackingEndStr = 'Some string that indicates the text is about to end'
SELECT
AField
,RTRIM(LTRIM(Substring(CAST([Body] AS VARCHAR(MAX))
,Charindex(@TrackingStartStr,CAST([Body] AS VARCHAR(MAX))) + LEN(@TrackingStartStr)
,charindex(@TrackingEndStr,CAST([Body] AS VARCHAR(MAX))) - (Charindex(@TrackingStartStr,CAST([Body] AS VARCHAR(MAX))) + LEN(@TrackingStartStr))
))) AS TrackingCode
From tbl_stupidTextTable
我不知道如何有条件地更改每行@TrackingEndStr
的内容。
答案 0 :(得分:0)
尝试:
select substring(stringfield,
charindex('/', stringfield, 1),
charindex(' ',
stringfield,
charindex('/', stringfield, 1)) -
charindex('/', stringfield, 1)) as val
from tbl
SQL小提琴演示:http://sqlfiddle.com/#!6/cebab/16/0