Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a LastIndexOf in SQL Server?

I am trying to parse out a value from a string that involves getting the last index of a string. Currently, I am doing a horrible hack that involves reversing a string:

SELECT REVERSE(SUBSTRING(REVERSE(DB_NAME()), 1,      CHARINDEX('_', REVERSE(DB_NAME()), 1) - 1)) 

To me this code is nearly unreadable. I just upgraded to SQL Server 2016 and I hoping there is a better way. Is there?

like image 223
AngryHacker Avatar asked Aug 17 '16 16:08

AngryHacker


People also ask

Is there a last function in SQL?

The LAST() function returns the last value of the selected column.

How do I get last 3 letters 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.


2 Answers

If you want everything after the last _, then use:

select right(db_name(), charindex('_', reverse(db_name()) + '_') - 1) 

If you want everything before, then use left():

select left(db_name(), len(db_name()) - charindex('_', reverse(db_name()) + '_')) 
like image 200
Gordon Linoff Avatar answered Sep 19 '22 09:09

Gordon Linoff


Wrote 2 functions, 1 to return LastIndexOf for the selected character.

CREATE FUNCTION dbo.LastIndexOf(@source nvarchar(80), @pattern char) RETURNS int BEGIN          RETURN (LEN(@source)) -  CHARINDEX(@pattern, REVERSE(@source))  END;   GO 

and 1 to return a string before this LastIndexOf. Maybe it will be useful to someone.

CREATE FUNCTION dbo.StringBeforeLastIndex(@source nvarchar(80), @pattern char) RETURNS nvarchar(80) BEGIN          DECLARE @lastIndex int        SET @lastIndex = (LEN(@source)) -  CHARINDEX(@pattern, REVERSE(@source))        RETURN SUBSTRING(@source, 0, @lastindex + 1)       -- +1 because index starts at 0, but length at 1, so to get up to 11th index, we need LENGTH 11+1=12 END;   GO 
like image 32
user2771704 Avatar answered Sep 19 '22 09:09

user2771704