I have a field in a table which consist of a string of values separated by semi-colons, e.g. apple; banana; orange; pear
I have been trying to build a SELECT statement to return the second group in between first and second semi-colons counting from the right (and if there is only 1 semi-colon will return null for now).
For example, orange.
I have been testing and trying ChatGPT but the closest I have gotten is of below, which returns everything right of the second semi-colon counting from the right.
As example: orange; pear
I just cannot figure out what I should do to not show anything value right of the first semi-colon on the right. Or could it be my dataset issue, as I do see sometimes commas were used instead of semi-colons but that could be another story too.
LTRIM(RTRIM(
CASE
-- Ensure there are more than two semicolons
WHEN LEN(@string) - LEN(REPLACE(@string, ';', '')) >= 2
THEN SUBSTRING(
@string,
LEN(@string) - CHARINDEX(';', REVERSE(@string), CHARINDEX(';', REVERSE(@string)) + 1) + 2,
CHARINDEX(';', REVERSE(@string), CHARINDEX(';', REVERSE(@string)) + 1) - 1
)
ELSE ''
END
)) AS SecondGroupFromRight
Would really appreciate some help. Many thanks in advance