How do I count varchar in a varchar using TSQL

99封情书 提交于 2019-12-24 03:16:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!