Some times we need to get the last occurrence of a character in any string , charindex returns with the index of first occurrence of a character but we can still use it by playing a small trick
consider an example
suppose we have a string 'C:\ProgramFiles\Test\Test.xml'
and we want to get file name i.e Test.xml
we can use Reverse method to get the occurrence of '\' character , like
Declare @FileName varchar(100)
Set @FileName = 'C:\ProgramFiles\Test\Test.xml'
Select Substring(@FileName,
LEN(@FileName ) -
Charindex('\',Reverse(@FileName ))+2,
LEN(@FileName ))
OR
we can use RIGHT Function like
DECLARE @FileName VARCHAR(255)
SET @FileName = 'C:\ProgramFiles\Test\Test.xml'
SELECT RIGHT( @FileName , CHARINDEX( '\', REVERSE( @FileName ) + '\' ) - 1 )
No comments:
Post a Comment