Get the 2nd or 3rd occurrence of a value in a delimited string
You can use cross apply
and the third parameter of charindex
to get the position of the underscores.
declare @T table
(
Name_Level_Class_Section varchar(25)
)
insert into @T values
('Jacky_1_B2_23'),
('Johnhy_1_B2_24'),
('Peter_2_A5_3')
select substring(Name_Level_Class_Section, P2.Pos + 1, P3.Pos - P2.Pos - 1)
from @T
cross apply (select (charindex('_', Name_Level_Class_Section))) as P1(Pos)
cross apply (select (charindex('_', Name_Level_Class_Section, P1.Pos+1))) as P2(Pos)
cross apply (select (charindex('_', Name_Level_Class_Section, P2.Pos+1))) as P3(Pos)
Result:
-------------------------
B2
B2
A5
Update: Using your table the query would look like this:
select *,
substring(Name_Level_Class_Section, P2.Pos + 1, P3.Pos - P2.Pos - 1) as CLA
from Bookings
cross apply (select (charindex('_', Name_Level_Class_Section))) as P1(Pos)
cross apply (select (charindex('_', Name_Level_Class_Section, P1.Pos+1))) as P2(Pos)
cross apply (select (charindex('_', Name_Level_Class_Section, P2.Pos+1))) as P3(Pos)
order by CLA asc,
Name_Level_Class_Section asc
Update 2:
If you know for sure that your value never contains a period .
and that it is always a four part name you can use parsename.
select *,
parsename(replace(Name_Level_Class_Section, '_', '.'), 2) as CLA
from Bookings
order by CLA asc,
Name_Level_Class_Section asc