我有一个名为description的文本字段,列出了很多信息,我想在特定的单词之间提取字符串。文本值示例:
一般福利:这样做的目的是解释使用我们产品的好处。
健康因素:请查看我们的网站以获取完整列表。
评论:此处输入用户添加的任何评论。
联系我们:请致电xxx-xxx-xxxx
一般福利,健康因素,评论和联系我们将始终在文本字段中,但每个之后的声明是不同的。 输出应该在这四个字符串之间提取字符串:
答案 0 :(得分:1)
这似乎就是你所追求的 - 希望它能够被使用。我确信有更好的方法可以做到这一点:)
为了完整性,我在临时表中创建了一个包含两行的测试用例,因为我假设您有许多行要处理。
CREATE TABLE #Test (Txt NVARCHAR(MAX))
INSERT INTO #Test (Txt) VALUES
(N'General Benefits: The purpose of this is to explain the benefits from using our products. Health Factors: Please check out our website for a complete list. Comments: Any comment added by the user is entered here. Contact Us: Please call us at xxx-xxx-xxxx'),
(N'General Benefits: Some other benefits. Health Factors: Some other factors. Comments: Love your work. Contact Us: Call us zzz-zzz-zzzz');
DECLARE @PAT1 NVARCHAR(MAX) = N'General Benefits:';
DECLARE @PAT2 NVARCHAR(MAX) = N'Health Factors:';
DECLARE @PAT3 NVARCHAR(MAX) = N'Comments:';
DECLARE @PAT4 NVARCHAR(MAX) = N'Contact Us:';
SELECT
SUBSTRING(Txt, A + LEN(@PAT1) + 1, B - A - LEN(@PAT1) - 1) 'General Benefits',
SUBSTRING(Txt, B + LEN(@PAT2) + 1, C - B - LEN(@PAT2) - 1) 'Health Factors',
SUBSTRING(Txt, C + LEN(@PAT3) + 1 , D - C - LEN(@PAT3) - 1) 'Comments',
SUBSTRING(Txt, D + LEN(@PAT4) + 1 , LEN(Txt) - LEN(@PAT4) - 1) 'Contact Us'
FROM #Test
CROSS APPLY (SELECT
A = PATINDEX('%'+@PAT1+'%', Txt),
B = PATINDEX('%'+@PAT2+'%',Txt),
C = PATINDEX('%'+@PAT3+'%',Txt),
D = PATINDEX('%'+@PAT4+'%',Txt)
) Q
General Benefits Health Factors Comments Contact Us
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The purpose of this is to explain the benefits from using our products. Please check out our website for a complete list. Any comment added by the user is entered here. Please call us at xxx-xxx-xxxx
Some other benefits. Some other factors. Love your work. Call us zzz-zzz-zzzz
(2 row(s) affected)