简体   繁体   English

如何计算SQL Server 2005中TEXT数据类型内字符串的出现次数

[英]How to count the occurrences of a string inside TEXT datatype in SQL Server 2005

There is a column of datatype TEXT in my table. 我的表中有一列数据类型为TEXT。 Now, I need to find the number of occurrences of a string in that TEXT field. 现在,我需要在该TEXT字段中找到一个字符串出现的次数。 I have already created a Full-text index on that table. 我已经在该表上创建了全文索引。 But I don't know how to proceed further. 但是我不知道该如何进一步。 I already found ways to count string occurrences for VARCHAR. 我已经找到了计算VARCHAR字符串出现次数的方法。 But they cannot be applied AS IS to TEXT field. 但是它们不能按原样应用于TEXT字段。 Any suggestions? 有什么建议么?

Try this: 尝试这个:

 declare @searchString varchar(max);
 set @searchString = 'something';
 declare @textTable table (txt text);
 insert into @textTable ( txt )
 values  ( 'something that has something 2 times' )

 select 
 (
  datalength(txt) - 
  datalength(replace(cast(txt as varchar(max)), @searchString, ''))
 )
 /datalength(@searchString) [Count]

   from @textTable as tt

Note that casting as varchar(max) won't truncate your text column as the max length of varchar(max) is 2^31-1 bytes or 2Gb. 请注意,强制转换为varchar(max)不会截断您的text列,因为varchar(max)的最大长度为2 ^ 31-1字节或2Gb。

Here's how to do it against an ntext: 这是针对ntext的方法:

    CREATE FUNCTION fn_CountInNText 
    (
        @SearchString nvarchar,
        @NTextToSearch ntext
    )
    RETURNS int
    AS
    BEGIN
        RETURN 
        (
        datalength(@NTextToSearch) - 
        datalength(replace(cast(@NTextToSearch as nvarchar(max)), @SearchString, ''))
        )
        /datalength(@SearchString)/2 
    END
    GO

Then select it something like this: 然后选择如下所示的内容:

SELECT dbo.fn_CountInNText('Something',[TheNTextColumn]) AS [Count] 
FROM [TheTable]

convert that(Text) field to varchar and find the count 将that(Text)字段转换为varchar并找到计数

eg : convert(varchar(200),textColumn) 例如: convert(varchar(200),textColumn)

Be aware of that if you use ntext instead of text, Denis Valeevs answer will not give you the correct answer. 请注意,如果您使用ntext而不是text,则Denis Valeevs的答案将无法为您提供正确的答案。

Text: Variable length non-unicode data with max length of 2,147,483,647 characters. 文本:可变长度的非Unicode数据,最大长度为2,147,483,647个字符。

nText: Variable lenght unicide data with max lenght of 1,073, 741, 823 characters. nText:可变长度非杀虫剂数据,最大长度为1,073、741、823个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM