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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Count # of times a pattern appears in a string 3

Status
Not open for further replies.

johnv20

Programmer
Sep 26, 2001
292
US
Does anyone have a quick way of counting the number of times a pattern appears in a string e.g. I need to count the number of times the expression 'ab' appears in the string 'ab xxxxabxx ab'.

I know I can use patindex to get the first location & keep shortening the string everytime its found, however going through this for tables with a large number of rows is proving very time consuming.
 
Dirty way:
Code:
select blah blah, (len(myfield) - len(replace(myfield, 'ab', '')))/len('ab')
from myTable
Looks ugly, but I guess it is less resource intensive than looping or UDF.

------
"There's a man... He's bald and wears a short-sleeved shirt, and somehow he's very important to me. I think his name is Homer."
(Jack O'Neill, Stargate)
[banghead]
 
vongrunt,

That is very clever. You replace the string with an empty string, and then determine how much smaller the original string got.

I would have gone with the UDF approach, but your solution is better.

Have a star just for thinking outside the box.

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top