I started with this, but is this the best way to complete the task?
select
reverse(
substring(reverse(some_field),
charindex('-', reverse(some_field)) + 1,
len(some_field) - charindex('-', reverse(some_field))))
from SomeTable
- How does SQL Server handle multiple calls
reverse(some_field)? - Besides UDF and iterating through a string looking for a
charindex
β-β and storing the last of its index, is there still an efficient way to accomplish this task in T-SQL?
Please note that I have work, I'm just wondering if this is the best way.
Below are some sample values ββfor some_field.
s2-st, s1-st, s3-st, s3-sss-zzz, s4-sss-zzzz
EDIT:
An example output for this would be ...
s1, s2, s3-sss, s3, s4-sss
The solution written by ErikE actually gets the end of the line, so everything after the last hyphen. I just changed its version to get everything before using a similar method with a function instead left. Thank you for your help.
select left(some_field, abs(charindex('-', reverse(some_field)) - len(some_field)))
from (select 's2-st' as some_field
union select 's1-st'
union select 's3-st'
union select 's3-sss-zzz'
union select 's4-sss-zzzz') as SomeTable