-1

I have a table which contains dashed strings.

I want string between last dash and second last dash

Dash means -

SQL Server table

Create table tbl1 (vdocno varchar(200))

insert into tbl1 values('Abcd-67-Hji-kok-74-Kio')
insert into tbl1 values('Bki-6kdi7-jhfi-Hfjdji-koikk-7ji4-Kloio')

Desired output values:

74
7ji4

SQLFIDDLE

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Hiren gardhariya
  • 1,247
  • 10
  • 29

1 Answers1

1

It's not the prettiest and I have no doubt it could be done more efficiently, but here's something that works that you could improve upon if required:

Demo SQL Fiddle

create table tbl1 (vdocno varchar(200))

insert into tbl1 values('Abcd-67-Hji-kok-74-Kio')
insert into tbl1 values('Bki-6kdi7-jhfi-Hfjdji-koikk-7ji4-Kloio')

select vdocno,
reverse(substring(
    reverse(substring(vdocno, 1, LEN(vdocno) - CHARINDEX('-',REVERSE(vdocno)))), 
         1, CHARINDEX('-',
                        reverse(substring(vdocno, 1, LEN(vdocno) - CHARINDEX('-',REVERSE(vdocno))))
                     ) 
         - 1))
from tbl1

This reverses the string and strips off the section before and including the last dash, then using the reserved string, it removes the content after the first dash, before reversing it to be the right way round again.

Tanner
  • 22,205
  • 9
  • 65
  • 83