August 15, 2008 at 9:35 am
Does anyone knows how to extract the last word
from a string. I got the first word from the below string,
but what I wanted is the last word in any string. is it possible? any help would be greatly appreciated.
declare @STR varchar(500)
declare @str2 int
declare @str3 varchar(500)
select @STR = 'you are working'
select @str2 = CHARINDEX(' ', @STR)
select @str2
select @str3 = SUBSTRING(@str, 1, @str2)
select @str3
August 15, 2008 at 9:48 am
Take a look at the REVERSE function. The steps would look something like this.
Initial string: you are working
Reversed: gnikrow era uoy
Extract first word: gnikrow
Reversed: working
August 15, 2008 at 9:55 am
Cool, it works. thanks a lot Todd. You are genius.
June 30, 2011 at 8:48 am
I just had a similar need - thanks - I got the arguments to charindex reversed. 🙂
For posterity:
ALTER FUNCTION [dbo].[HCA_FindLastWord](@InString nvarChar(Max)) RETURNS nvarchar(max)
AS
BEGIN
declare @stringLenint
declare @fragLenint
declare @sRtnnVarChar(Max)
SET @InString = RTRIM(LTRIM(@Instring))
set @stringLen = Len(@InString)
set @Fraglen = CharIndex( ' ', Reverse(RTRIM(@InString)) )
if @FragLen = 0
begin
set @sRtn = ''
end
else
if @FragLen = @stringLen
begin
set @sRtn = ''
end
else
BEGIN
set @sRtn = substring(@Instring, @Stringlen - @Fraglen, @Fraglen)
END
return ltrim(RTRIM(@srtn))
END
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply