Provided that there will be 3, and only 3, hyphens (-
) in the value of Code
, you could do:
SELECT Code,
RIGHT(Code, LEN(Code) - CI1.CI) AS C1,
RIGHT(Code, LEN(Code) - CI2.CI) AS C2, --One you're after
RIGHT(Code, LEN(Code) - CI3.CI) AS C3
FROM (VALUES ('name-surname-15A-15B')) V(Code)
CROSS APPLY (VALUES(CHARINDEX('-',V.Code))) CI1(CI)
CROSS APPLY (VALUES(CHARINDEX('-',V.Code,CI1.CI+1))) CI2(CI)
CROSS APPLY (VALUES(CHARINDEX('-',V.Code,CI2.CI+1))) CI3(CI);
You can easily expand this for more than that; however, if you have quite a lot of delimiters, I'd suggest looking into a string splitter, and then using FOR XML PATH
to concatenate the string back together. Edit: Or STRING_AGG
of you're using SQL Server 2017.