Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tsql last "occurrence of" inside a string

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?

like image 757
Alberto De Caro Avatar asked Feb 28 '12 09:02

Alberto De Caro


People also ask

How do you find the last occurrence of a character in a string in SQL?

You can use the Reverse Function to find the last occurrance. Quickest way is to reverse the string and look for the first occurrence.

How do I get the last substring in SQL?

To get the first n characters of string with MySQL, use LEFT(). To get the last n char of string, the RIGHT() method is used in MySQL.

How can I get the last index of a character in SQL Server?

It should be: select left(db_name(), len(db_name()) - charindex('_', reverse(db_name()) + '_') + 1) (I tried to edit, but the change had to be at least 6 characters.) – Joakim M. H.

How do you check if a substring is present in a string in SQL?

SQL Server CHARINDEX() Function The CHARINDEX() function searches for a substring in a string, and returns the position. If the substring is not found, this function returns 0. Note: This function performs a case-insensitive search.


1 Answers

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)

like image 104
Alex K. Avatar answered Sep 27 '22 21:09

Alex K.