问题
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 HELLO 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
回答1:
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.
来源:https://stackoverflow.com/questions/6641765/how-do-i-count-varchar-in-a-varchar-using-tsql