如何使用SQL计算varchar中的varchar

时间:2011-07-10 14:51:18

标签: sql tsql textmatching

计算varchar中varchar出现次数的最佳方法是什么。

我宁愿不循环浏览文本以找到某些组合。

此选择仅查找第一个

SELECT CASE WHEN CHARINDEX('!','HOW MANY TIMES IS ! IN THIS TEXT ? THIS IS MY QUESTION !' ) > 0 THEN 1 ELSE 0 END

返回1

我需要一种方法来查找匹配总数

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

预期结果

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

使用mssql server 2005

1 个答案:

答案 0 :(得分:6)

您可以使用replace使每次出现更长1个字符,并计算添加的字符数:

select  len(replace(txt, search, search + '#')) - len(txt) as Count
,       *
from    YourTable

Full example at SE Data.