简体   繁体   中英

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. Now, I need to find the number of occurrences of a string in that TEXT field. 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. But they cannot be applied AS IS to TEXT field. 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.

Here's how to do it against an 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

eg : 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.

Text: Variable length non-unicode data with max length of 2,147,483,647 characters.

nText: Variable lenght unicide data with max lenght of 1,073, 741, 823 characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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