简体   繁体   中英

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.

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.

Thanks for any help

If you always the same number of elements you could leverage PARSENAME like this.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM