如何使用 t-sql 获取字符串中的第二个单词?
How to get the second word in a string using t-sql?
我想从第一个和第三个空格之间的字符串或短语中提取第二个单词。
例如
'The Boeing Corporation'
我要'Boeing'
declare @sentence nvarchar(264);
set @sentence = 'The Boeing Corporation';
select ltrim(substring(@sentence,charindex(' ',@sentence), CHARINDEX(' ',ltrim(SUBSTRING(@sentence,charindex(' ',@sentence),LEN(@sentence)-charindex(' ',@sentence)))) ))
| (No column name) |
| :--------------- |
| Boeing |
db<>fiddle here
只是另一种选择 XML
例子
Declare @YourTable table (SomeCol varchar(500))
Insert Into @YourTable values
('The Boeing Corporation')
Select SomeCol
,Pos2 = cast('<x>' + replace(A.SomeCol,' ','</x><x>')+'</x>' as xml).value('/x[2]','varchar(50)')
From @YourTable A
Returns
SomeCol Pos2
The Boeing Corporation Boeing
我想从第一个和第三个空格之间的字符串或短语中提取第二个单词。
例如
'The Boeing Corporation'
我要'Boeing'
declare @sentence nvarchar(264); set @sentence = 'The Boeing Corporation'; select ltrim(substring(@sentence,charindex(' ',@sentence), CHARINDEX(' ',ltrim(SUBSTRING(@sentence,charindex(' ',@sentence),LEN(@sentence)-charindex(' ',@sentence)))) ))
| (No column name) | | :--------------- | | Boeing |
db<>fiddle here
只是另一种选择 XML
例子
Declare @YourTable table (SomeCol varchar(500))
Insert Into @YourTable values
('The Boeing Corporation')
Select SomeCol
,Pos2 = cast('<x>' + replace(A.SomeCol,' ','</x><x>')+'</x>' as xml).value('/x[2]','varchar(50)')
From @YourTable A
Returns
SomeCol Pos2
The Boeing Corporation Boeing