2014-03-26 112 views
0

我想使用ContainsTable來獲取嵌入在名爲description的t-sql nvarchar列中的單個單詞的計數。如果我提供紅色或綠色的標準,我怎麼知道哪一個實際匹配?簡而言之,我正在努力進行單詞統計,並正在尋找最佳方法。t-sql:在varchar列中計算單詞的出現次數

在此先感謝

+0

安置自己當前或查詢 – Paparazzi

+0

看到這個答問: http://stackoverflow.com/questions/738282/how-do-you-count-the-number-of-occurrences-of-a-certain -substring-IN-A-SQL varch –

回答

0

在這裏你去:

drop function dbo.CountOccurrencesOfWord 
go 

create function dbo.CountOccurrencesOfWord(
    @text varchar(max), 
    @word varchar(8000) 
) 
returns int 
as 
begin 
    declare 
     @index int = charindex(@word, @text, 1), 
     @len int = len(@word), 
     @count int = 0 
    while @index > 0 begin    
     set @count = @count + 1 
     set @index = charindex(@word, @text, @index + @len) 
    end 
    return @count 
end 

GO 

if object_id('tempdb..#example') is not null 
    drop table #example 
create table #example(
    description nvarchar(4000) not null 
) 

insert into #example select 'red yellow green red white blue red redred red green red' 
insert into #example select 'red yellow green red' 
insert into #example select 'orange grey green' 
insert into #example select '' 
insert into #example select 'magenta aqua cyan' 

select dbo.CountOccurrencesOfWord(description, 'red'), description 
from #example 

caution-的單詞這樣的邏輯可以在T-SQL相當昂貴的。

相關問題