如何从SQL Server中的文本中获得第三个单词



是否有人可以帮助查询从SQL Server中的文本中获得第3个单词?下面的查询检索第二个单词,但我需要第三个单词。谢谢。

SELECT substring(@sentence,charindex(' ',@sentence), CHARINDEX(' ',ltrim(SUBSTRING(@sentence,charindex(' ',@sentence),LEN(@sentence)-charindex(' ',@sentence)))) )

使用一点JSON你可以得到第三个单词

Select * 
,NewVal = JSON_VALUE('["'+replace(string_escape(SomeCol,'json'),' ','","')+'"]' ,'$[2]')
From YourTable

或者使用一些更健壮的东西,使用CROSS APPLY

Select A.*
,Pos1 = JSON_VALUE(JS,'$[0]')
,Pos2 = JSON_VALUE(JS,'$[1]')
,Pos3 = JSON_VALUE(JS,'$[2]')
,Pos4 = JSON_VALUE(JS,'$[3]')
From YourTable A
Cross Apply (values ( '["'+replace(string_escape(SomeCol,'json'),' ','","')+'"]' ) ) B(JS)

如果使用变量

Declare @sentence varchar(max) = 'This is only a test'
Select JSON_VALUE('["'+replace(string_escape(@sentence,'json'),' ','","')+'"]' ,'$[2]')

最新更新