2014-09-10 33 views
1

塊我對SQL服務器的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的例子工作正常,但顯然在文本中沒有完全停止沒有返回。

任何人有任何明智的想法,我可以如何實現這一目標?

回答

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

謝謝,非常感謝。我覺得我最喜歡這個! – 2014-09-11 20:03:48

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