我有SQL服务器的以下SQL:
declare @summary1 as nvarchar(max)
declare @summary2 as nvarchar(max)
set @summary1='this is some long text. this is the rest of the text'
set @summary2='some text with no full stops'
select substring(@summary1, 1,CHARINDEX('.', @summary1)) as sentence
select substring(@summary2, 1,CHARINDEX('.', @summary2)) as sentence
我希望能够从“摘要”中获取第一句话,如果没有句号,则返回所有文本。 @ summary1的示例工作正常但很明显,文本中没有完全停止,不返回任何内容。
任何人都有任何明智的想法如何实现这一目标?
答案 0 :(得分:3)
我会使用CASE
表达式:
SELECT
CASE CHARINDEX('.', @summary1) -- determine if the sentence contains a full stop
WHEN 0 THEN @summary1 -- if not return the whole sentence
ELSE SUBSTRING(@summary1, 1, CHARINDEX('.', @summary1)) -- else first part
END AS sentence
答案 1 :(得分:1)
怎么样
select substring(@summary1, 1,CHARINDEX('.', @summary1)) as sentence
select substring(@summary2, 1,CHARINDEX('.', @summary2+'.')) as sentence
这将在行的末尾添加一个停止,即使它在那里。你可以设置if / else语句来确定最后是否有一个点,并相应地附加一个。
@summary2
返回some text with no full stops