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!

Occurs function ?

Status
Not open for further replies.

fluteplr

Programmer
Oct 23, 2000
1,599
US
Is there a an function in SQL server, or some other trick that would return the number of times a particular string occurs within another string.

For example the field bigstring = 'AAABCDDD'

occurs('A',bigstring)=3
occurs('ABC',bigstring)=1

thanks

 
You can create your own function like this...


CREATE FUNCTION Occurs (
@findstr varchar(100),
@mystr varchar(100)
)
RETURNS int
AS
BEGIN
DECLARE @cnt int
SET @cnt = 0
WHILE CHARINDEX(@findstr, @mystr, 1) <> 0
BEGIN
SET @cnt = @cnt + 1
SET @mystr = SUBSTRING(@mystr, CHARINDEX(@findstr, @mystr, 1) + 1, 100)
END
RETURN(@cnt)
END


And then execute it like this...

SELECT dbo_Occurs('A', 'AAABCDDD')


Andel
andelbarroga@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top