【发布时间】:2018-05-06 14:12:56
【问题描述】:
我在 SQL Server DB 表中有一个 varchar(max) 字段,我想在该字段中查找所有出现的字符串,并在读取时为其提供 50 个字符的上下文。
我已经使用下面的代码完成了这项工作,但现在我想对其进行调整,使其适用于所有出现的字符串,并使其出现在一个字段中。
declare @extract varchar(max)
set @extract =
'As Harry squelched along the deserted corridor he came across somebody who looked just as preoccupied as he was. Nearly Headless Nick, the ghost of Gryffindor Tower, was staring morosely out of a window, muttering under his breath, ". . . don''t fulfill their requirements . . . half an inch, if that . . ."
"Hello, Nick," said Harry.
"Hello, hello," said Nearly Headless Nick, starting and looking round. He wore a dashing, plumed hat on his long curly hair, and a tunic with a ruff, which concealed the fact that his neck was almost completely severed. He was pale as smoke, and Harry could see right through him to the dark sky and torrential rain outside.
"You look troubled, young Potter," said Nick, folding a transparent letter as he spoke and tucking it inside his doublet.
"So do you," said Harry.'
declare @searchterm varchar(max)
set @searchterm = '%Harry%'
declare @searchtermlength int = len(@searchterm)
declare @stringFrom int = (select PATINDEX(@searchterm,@extract) - 50 )
declare @stringto int = (select PATINDEX(@searchterm,@extract) + @searchtermlength + 50 )
declare @noChars int = @stringto - @stringfrom
select SUBSTRING(@extract,@stringFrom,@noChars)
这将返回'As Harry squelched along the deserted corridor he came acros',但我希望它返回:
As Harry squelched along the deserted corridor he came acros...
...f an inch, if that . . ." "Hello, Nick," said Harry. "Hello, hello," said Nearly Headless Nick, sta
...ost completely severed. He was pale as smoke, and Harry could see right through him to the dark sky and tor...
...king it inside his doublet. "So do you," said Harry.
我猜这可以使用循环来完成,但我之前从未真正使用过循环,因此非常感谢任何帮助。
提前致谢
【问题讨论】:
-
这与光标无关,但不清楚你在这里真正想要完成什么......
-
很抱歉错误地假设这将使用光标。正如我所说,我对他们的经验很少。我不知道如何才能更清楚,我已经提供了我当前的代码、当前输出和所需的输出。你能告诉我我错过了什么,我会编辑我的帖子。
标签: sql tsql for-loop substring patindex