[英]Selecting text between 2nd and 3rd occurrence of delimiter
I'm trying to select the text between the second and third occurance of a delimeter (-) in SQL server.我正在尝试 select 服务器中第二次和第三次出现分隔符 (-) 之间的文本。
For example, if I have the string aaa-bbbb-cccc-dddd
I would like to return cccc
, but I can't understand how to make a substring work when I have more than 2 of the delimeters.例如,如果我有字符串aaa-bbbb-cccc-dddd
我想返回cccc
,但是当我有超过 2 个分隔符时,我不明白如何使 substring 工作。
Thanks for any help谢谢你的帮助
If you always the same number of elements you could leverage PARSENAME like this.如果您始终使用相同数量的元素,则可以像这样利用 PARSENAME。
select parsename(replace('aaa-bbbb-cccc-dddd', '-', '.'), 2)
But if your real data is not that consistent you need to use a real splitter.但是,如果您的真实数据不是那么一致,则需要使用真正的拆分器。
If parsename()
(+1) is not a valid option, perhaps a little XML.如果parsename()
(+1) 不是一个有效的选项,可能有点 XML。
Here are two illustrations, both return the same results这是两个插图,都返回相同的结果
Example例子
Declare @YourTable table (SomeCol varchar(500))
Insert Into @YourTable values
('aaa-bbbb-cccc-dddd')
Select SomeCol
,Pos2 = cast('<x>' + replace(A.SomeCol,'-','</x><x>')+'</x>' as xml).value('/x[2]','varchar(50)')
,Pos3 = cast('<x>' + replace(A.SomeCol,'-','</x><x>')+'</x>' as xml).value('/x[3]','varchar(50)')
From @YourTable A
Select SomeCol
,B.*
From @YourTable A
Cross Apply (
Select Pos2 = XMLData.value('/x[2]','varchar(50)')
,Pos3 = XMLData.value('/x[3]','varchar(50)')
From (values (cast('<x>' + replace(A.SomeCol,'-','</x><x>')+'</x>' as xml))) B1(XMLData)
) B
Returns退货
SomeCol Pos2 Pos3
aaa-bbbb-cccc-dddd bbbb cccc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.