我应该如何计算变量aaa中的单词“asdf”,其值为“asdf_dd_adf34asdf_sdf”?
DECLARE @aaa varchar;
SET @aaa = 'asdf_dd_adf34asdf_sdf';
答案 0 :(得分:3)
如果删除单词的出现次数,则计算消失的字符数,并除以单词的长度:
(len(aaa) - len(replace(aaa, 'asdf', ''))) / len('asdf')
答案 1 :(得分:1)
注意:我添加了基于XQuery count function的其他解决方案。
如果您只想计算“完全单词”,那么您可以使用以下解决方案之一:
SET ANSI_WARNINGS ON;
DECLARE @Source VARCHAR(200)
SET @Source = 'asdf_dd_adf34asdf_sdf_asdf_coco_jambo';
DECLARE @x XML = (SELECT @Source FOR XML PATH(''))
SET @x = N'<root> <word>' + REPLACE(CONVERT(VARCHAR(200),@x), N'_', N'</word> <word>') + N'</word> </root>';
DECLARE @Parameter VARCHAR(200) = 'asdf' ;
--Solution 1
SELECT @x.query('count( //root/word[text()=sql:variable("@Parameter")] )').value('(.)','INT') AS WordCount_Solution1;
--Solution 2
SELECT COUNT(*) AS WordCount_Solution2
FROM
(
SELECT n.t.value('(.)','VARCHAR(200)') AS Word
FROM @x.nodes('root/word') AS n(t)
) src
WHERE src.Word = @Parameter;
结果:
WordCount_Solution1
-------------------
2
WordCount_Solution2
-------------------
2