March 25, 2004 at 12:34 am
Hi,
I want to get the last occurance of a string/char in a given string.
is there any implicit function for doing so similar to CAHRINDEX that returns the first occurance.
Thanks in advance
-Prasad
Prasad Bhogadi
www.inforaise.com
March 25, 2004 at 3:33 am
Select Len('Dianesh Asanka') - CHARINDEX(reverse('an'),reverse ('Dianesh Asanka'),0) - 1
Not sure above is correct
But u can use CharIndex,reverse,Len functions to achive this
My Blog:
March 26, 2004 at 2:40 am
I saw the script "Function To Retrieve Last Index ". I do not understand why it is so complicated. THis script does the same :
create function dbo.LastIndexOf
(
@strValue varchar(4000),
@strChar varchar(50)
)
returns integer
as
begin
declare @ndx int
set @ndx = charindex(reverse(@strChar),reverse(@strValue))
if @ndx is null OR @ndx = 0 return @ndx
return len(@strValue) - @ndx - len(@strChar) + 2
end
March 26, 2004 at 4:13 am
Hi Bert,
After I posted that question, I wrote the above script and thought it may be useful for some more people, so posted it in scripts because I didnot find any direct function which accomplishes the said functionality, however any optimizations would be appreciated.
Thanks
Prasad Bhogadi
www.inforaise.com
March 26, 2004 at 9:11 am
One caveat: There may be leading or trailing blank(s) in a string. In that case LEN() of the original string could differ from the LEN() of the reversed string. Use DATALENGTH() instead for correctness.
March 26, 2004 at 9:24 am
DATALENGTH returns the number of bytes, and not the number of characters ( this is not the same ) But Len returns : "Returns the number of characters, rather than the number of bytes, of the given string expression, excluding trailing blanks". To make sure there are no trailing blanks, I propose this solution :
create function dbo.LastIndexOf
(
@strValue varchar(4000),
@strChar varchar(50)
)
returns integer
as
begin
declare @ndx int
set @ndx = charindex(reverse(@strChar),reverse(@strValue))
if @ndx is null OR @ndx = 0 return @ndx
return len(@strValue+'X') - @ndx - len(@strChar+'X') + 2
end
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply