April 8, 2009 at 7:27 am
Hi All,
I am trying to find the last occurence of a character within a string. I have the following code: what is the easiest way to accomplish this?
SELECT CASE WHEN FieldA IS NULL THEN '' ELSE
set @pos = charindex('\',FieldA,@pos)
while(@pos)>0
begin
set @lastpos=@pos
set @pos=charindex('\',FieldA,@pos+1)
end
SUBSTRING(FieldA ,@pos + 1, LEN(FieldA) - (@pos + 1)) END AS FileUploaded
FROM TableA
Example data of FieldA : "DirectoryA\DirectoryB\DirectoryC\FileName"
"DirectoryA\DirectoryB\FileName"
Thank you.
April 8, 2009 at 7:44 am
You can use the Reverse Function to find the last occurrance.
Declare @FieldA varchar(100)
Set @FieldA = 'DirectoryA\DirectoryB\DirectoryC\FileName'
Select Substring(@FieldA,
LEN(@FieldA) -
Charindex('\',Reverse(@FieldA))+2,
LEN(@FieldA))
April 8, 2009 at 7:49 am
Quickest way is to reverse the string and look for the first occurrence.
DECLARE @StringA varchar(100), @pos int
SET @stringA = 'DirectoryA\DirectoryB\FileName'
-- Where is the last '\'?
SET @pos = LEN(@StringA) - CHARINDEX('\',REVERSE(@StringA))
SELECT @pos
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
April 8, 2009 at 7:52 am
Or this way too...
DECLARE @SomeFile VARCHAR(255)
SET @SomeFile = 'C:\WINDOWS\system32\FileName.xls'
SELECT RIGHT( @SomeFile, CHARINDEX( '\', REVERSE( @SomeFile ) + '\' ) - 1 )
--Ramesh
April 8, 2009 at 8:04 am
Ramesh (4/8/2009)
Or this way too...
DECLARE @SomeFile VARCHAR(255)
SET @SomeFile = 'C:\WINDOWS\system32\FileName.xls'
SELECT RIGHT( @SomeFile, CHARINDEX( '\', REVERSE( @SomeFile ) + '\' ) - 1 )
Perfect solution..with simple trick using REVERSE...
April 8, 2009 at 8:08 am
If you're looking to retrieve the filename from a path, then this seems to do the job:
SELECT FieldA, COALESCE(RIGHT(FieldA, NULLIF(CHARINDEX('\', REVERSE(FieldA)) - 1, -1)), FieldA, '') AS Filename
FROM (
SELECT 'DirectoryA\DirectoryB\DirectoryC\FileName1' AS FieldA UNION ALL
SELECT 'DirectoryA\DirectoryB\FileName2' UNION ALL
SELECT 'FileName3' UNION ALL
SELECT 'DirectoryA\DirectoryB\' UNION ALL
SELECT '' UNION ALL
SELECT NULL
) TableA
April 8, 2009 at 8:28 am
Thank you Ken Simmons, that worked. Have a nice day.
May 4, 2010 at 5:48 pm
Nice little bit of Code, Thanks!
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy