What is the best way to count the occurence of a varchar within a varchar.
I rather not loop through a text in order to find certain combinations.
This select only find the first
SELECT CASE WHEN CHARINDEX('!','HOW MANY TIMES IS ! IN THIS TEXT ? THIS IS MY QUESTION !' ) > 0 THEN 1 ELSE 0 END
Returns 1
I need a method to find the total number of matches
TABLE DATA
SEARCHTEXT LONGTEXT
! HOW MANY TIMES IS ! IN THIS TEXT ? THIS IS MY QUESTION !
HELLO HELLO HELLO HELLO HELL开发者_运维技巧O HELLO HELLO
L HELLO HELLO HELLO HELLO HELLO HELLO
e more testdata
Expected result
Count SEARCHTEXT LONGTEST
2 ! MANY TIMES IS ! IN THIS TEXT ? THIS IS MY QUESTION !
6 HELLO HELLO HELLO HELLO HELLO HELLO HELLO
12 L HELLO HELLO HELLO HELLO HELLO HELLO
2 e more testdata
Using mssql server 2005
You could use replace
to make each occurrence 1 character longer, and count the number of added characters:
select len(replace(txt, search, search + '#')) - len(txt) as Count
, *
from YourTable
Full example at SE Data.
精彩评论