Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2005:charindex starting from the end

I have a string 'some.file.name',I want to grab 'some.file'.

To do that,I need to find the last occurrence of '.' in a string.

My solution is :

 declare @someStr varchar(20)

 declare @reversedStr varchar(20)

 declare @index int

 set @someStr = '001.002.003'

 set @reversedStr = reverse(@someStr)

 set @index = len(@someStr) - charindex('.',@reversedStr)

 select left(@someStr,@index)

Well,isn't it too complicated?I was just intented to using 'some.file' in a where-clause.

Anyone has a good idea?

like image 928
Shuo Avatar asked Dec 05 '09 09:12

Shuo


People also ask

How do I get the last Charindex 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 does Charindex work in SQL Server?

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.

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

Searching from the start of a string expression. This example returns the first location of the string is in string This is a string , starting from position 1 (the first character) of This is a string . SELECT CHARINDEX('is', 'This is a string'); Here is the result set.


1 Answers

What do you need to do with it?? Do you need to grab the characters after the last occurence of a given delimiter?

If so: reverse the string and search using the normal CHARINDEX:

declare @test varchar(100)
set @test = 'some.file.name'

declare @reversed varchar(100)
set @reversed = REVERSE(@test)

select 
    REVERSE(SUBSTRING(@reversed, CHARINDEX('.', @reversed)+1, 100))

You'll get back "some.file" - the characters up to the last "." in the original file name.

There's no "LASTCHARINDEX" or anything like that in SQL Server directly. What you might consider doing in SQL Server 2005 and up is great a .NET extension library and deploy it as an assembly into SQL Server - T-SQL is not very strong with string manipulation, whereas .NET really is.

like image 162
marc_s Avatar answered Sep 23 '22 21:09

marc_s