Here is one answer that searches a string in reverse order for the second forward slash and returns that substring with forward slashes removed:
declare @s varchar(20)
set @s = 'A/B/C/D/E/F'
-- result: 'EF'
select reverse(replace(left(reverse(@s), charindex('/', reverse(@s), charindex('/', reverse(@s)) + 1)), '/', ''))
set @s = 'AB/CD/EF/GH'
-- result: 'EFGH'
select reverse(replace(left(reverse(@s), charindex('/', reverse(@s), charindex('/', reverse(@s)) + 1)), '/', ''))
Testing this with a couple of other inputs:
set @s = '/AB/CD' -- result: 'ABCD'
set @s = 'AB/CD' -- result: an empty string '' -- you may not want this result
set @s = 'AB' -- result: an empty string ''
Here is a ridiculously complicated way to do the same thing with a series of common table expressions (CTEs). Credit goes to Itzik Ben-Gan for the CTE technique to generate a tally table using cross-joins:
declare @s varchar(50)
set @s = 'A/B/C/D/E/F/G'
--set @s = 'AB/CD/EF/GH'
--set @s = 'AB/CD'
--set @s = 'ABCD/EFGH/IJKL'
--set @s = 'A/B'
-- set @s = 'A'
declare @result varchar(50)
set @result = ''
;with
-- cross-join a meaningless set of data together to create a lot of rows
Nbrs_2 (n) AS (SELECT 1 UNION SELECT 0 ),
Nbrs_4 (n) AS (SELECT 1 FROM Nbrs_2 n1 CROSS JOIN Nbrs_2 n2),
Nbrs_16 (n) AS (SELECT 1 FROM Nbrs_4 n1 CROSS JOIN Nbrs_4 n2),
Nbrs_256 (n) AS (SELECT 1 FROM Nbrs_16 n1 CROSS JOIN Nbrs_16 n2),
Nbrs_65536(n) AS (SELECT 1 FROM Nbrs_256 n1 CROSS JOIN Nbrs_256 n2),
Nbrs (n) AS (SELECT 1 FROM Nbrs_65536 n1 CROSS JOIN Nbrs_65536 n2),
-- build a table of numbers from the data above; this is insanely fast
nums(n) as
(
select row_number() over(order by n) from Nbrs
),
-- split the string into separate rows per letter
letters(n, c) as
(
select n, substring(@s, n, 1)
from nums
where n < len(@s) + 1
),
-- count the slashes from the rows in descending order
-- the important slash is the second one from the end
slashes(n, num) as
(
select n, ROW_NUMBER() over (order by n desc)
from letters
where c = '/'
)
select @result = @result + c
from letters
where n > (select n from slashes where num = 2) -- get everything after the second slash
and c <> '/' -- and drop out the other slash
select @result