|
|
|
Valued Member
      
Group: General Forum Members
Last Login: Wednesday, November 05, 2008 2:49 PM
Points: 57,
Visits: 14
|
|
|
|
|
|
Forum Newbie
      
Group: General Forum Members
Last Login: Wednesday, December 02, 2009 4:55 AM
Points: 1,
Visits: 2
|
|
helped me alot, thnx
|
|
|
|
|
SSCommitted
      
Group: General Forum Members
Last Login: Yesterday @ 9:53 AM
Points: 1,501,
Visits: 18,208
|
|
I suspect this would be more efficient with a numbers/tally table
declare @TargetStr varchar(8000), @SearchedStr varchar(8000), @Occurrence int set @TargetStr='a' set @SearchedStr='abbabba' set @Occurrence=3;
WITH Occurrences AS ( SELECT Number, ROW_NUMBER() OVER(ORDER BY Number) AS Occurrence FROM master.dbo.spt_values WHERE Number BETWEEN 1 AND LEN(@SearchedStr) AND type='P' AND SUBSTRING(@SearchedStr,Number,LEN(@TargetStr))=@TargetStr) SELECT Number FROM Occurrences WHERE Occurrence=@Occurrence
____________________________________________________
How to get the best help on a forum
http://www.sqlservercentral.com/articles/Best+Practices/61537
Never approach a goat from the front, a horse from the rear, or a fool from any direction.
|
|
|
|
|
Forum Newbie
      
Group: General Forum Members
Last Login: Thursday, April 21, 2011 8:35 AM
Points: 1,
Visits: 3
|
|
Looks wrong, if you go more than 1 above the maximum char number then it will loop through again.
if you change the WHILE statement from while (@counter < @Occurrence)
to while (@counter < @Occurrence) and @pos <> 0 that should fix the issue
Try running below
DECLARE @TXT varchar(255) SET @TXT = 'Michael Williamson' SELECT dbo.CHARINDEX2('l',@TXT,1) SELECT dbo.CHARINDEX2('l',@TXT,2) SELECT dbo.CHARINDEX2('l',@TXT,4) SELECT dbo.CHARINDEX2('l',@TXT,6)
Hope that helps
|
|
|
|
|
Forum Newbie
      
Group: General Forum Members
Last Login: Thursday, January 20, 2011 4:02 AM
Points: 1,
Visits: 3
|
|
Thanks! I found this function really useful. Just adding the middle line here got around the looping issue for me:
set @pos = @ret
if @pos = 0 set @counter = @Occurrence
end
|
|
|
|