tsql last “occurrence of” inside a string

泪湿孤枕 提交于 2019-12-09 03:32:26

问题


I have got field containing comma separated values. I need to extract the last element in the list. I have tried with this:

select list_field, LTRIM(RTRIM(right(list_field, len(list_field) - CHARINDEX(',',list_field))))

But it returns the last part of the list just starting after the first comma occurrence. For example,

a,b returns b

a,b,c returns b,c

I would like to use a regex like pattern. Is it possible in TSQL (sql server 2008)? Any other clues?


回答1:


Find the last , by reversing the string and looking for the first occurrence, then read that many characters from the right of the string;

rtrim(right(list_field, charindex(',', reverse(list_field)) - 1))

(Use reverse(list_field) + ',' if there is the possibility of no delimiters in the field & you want the single value)



来源:https://stackoverflow.com/questions/9479843/tsql-last-occurrence-of-inside-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!