Last n Characters

Hi. I have a string that is a mixture of characters and numbers and ends with either 4 or 5 numbers preceded by an underscore. How do I chop the string to get the last 4 (or 5) numbers after the underscore? Assuming I can't use RIGHT as I don't know how whether it will be 4 or 5 numbers. So I guess I need something that references the underscore and then take the numbers that fall directly after it. Thanks.

(SQL Server 2016)

SELECT STUFF(@yourString,1,CHARINDEX('_',@yourString+'_'),'')

Hi. Thanks. This takes all entries after the first underscore. I need entries after the last.

select right(@yourstring,charindex('_',reverse(@yourstring)+'_')-1);
1 Like