开发者

How do I count varchar in a varchar using TSQL

开发者 https://www.devze.com 2023-03-19 09:17 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号