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 4 (of 4 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