function to count occurences of substring in a string

Hi Experts,

I'm looking for a function to count occurences of a word / substring in a string...
I have seen this - http://sqlblog.com/blogs/adam_machanic/archive/2006/07/12/counting-occurrences-of-a-substring-within-a-string.aspx but I was hoping for something a bit simpler.

Many thanks!
  Dmitri
CallConnectionAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

TimCotteeHead of Software ServicesCommented:
If you want an exact count then:

Declare @Match varchar(100)
Set @Match='Hello'
Select (DataLength(MyField) - DataLength(Replace(MyField,@Match,''))) / DataLength(@Match)

For example.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CallConnectionAuthor Commented:
Thanks, here's My SQL version:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[GetSubstringCount](@s varchar(8000), @countthis varchar(8000))
RETURNS INT --WITH SCHEMA BINDING AS
BEGIN	
	RETURN 	
	(		SELECT (len(@s)-len(replace(@s,@countthis,'')))/(case when len(@countthis) = 0 then 1 else len(@countthis) end)
	)
END

Open in new window

0
CallConnectionAuthor Commented:
Tim,
  Your principle was right - I did my version at the same time..
Cheers,
  Dmitri
0
CallConnectionAuthor Commented:
I was hoping for a function, - but thank you vey much for the code.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.