Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

string expression occurance (easy)

Status
Not open for further replies.

youngun

Programmer
Apr 27, 2001
61
US
Is there any built-in function for searching the number of times a particular expression happens in a string?

For example, I want to know how many times 'D' happens in 'DADDY'.

Thanks a lot.
 
i don't think there is a built in function but you can create your own in sql2000
try this:
create function strCount (@lookfor char(1), @lookin varchar(20))
returns int
as
begin
declare @position int
set @position = 1
declare @count int
set @count = 0
while @position between 1 and len(@lookin)
begin
set @position = charindex(@lookfor,@lookin,@position)
if @position <> 0
begin
set @position = @position + 1
set @count = @count + 1
end
end

return @count
end

then call it like this:
select dbo.strCount('d','daddy')
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top