Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best way to get last indexof character in SQL 2008 [duplicate]

In C#, we have String.LastIndexOf method to get a last index of a particular character location for given string. Is there any similar function to do same in SQL Server. I tried using CHARINDEX but couldn't able to achieve it.

like image 225
Mahender Avatar asked Mar 29 '13 18:03

Mahender


People also ask

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

If you want to get the index of the last space in a string of words, you can use this expression RIGHT(name, (CHARINDEX(' ',REVERSE(name),0)) to return the last word in the string.

How do I get the last 3 characters of a string in SQL?

SELECT *FROM yourTableName ORDER BY RIGHT(yourColumnName,3) yourSortingOrder; Just replace the 'yourSortingOrder' to ASC or DESC to set the ascending or descending order respectively. Here is the query to order by last 3 chars. Case 1 − Get the result in ascending order.

What returns the index of the last instance of the character?

Using rfind() function A simple solution to find the last index of a character in a string is using the rfind() function, which returns the index of the last occurrence in the string where the character is found and returns -1 otherwise.


1 Answers

A little tricky, but you could do something like:

REVERSE(SUBSTRING(REVERSE([field]),0,CHARINDEX('[char]',REVERSE([field])))) 
like image 59
antinescience Avatar answered Oct 02 '22 19:10

antinescience