如果您使用的是SQL Server 2008中,您可以使用全文解析器來分割你的字符串:
Declare @Inputs Table (Id int not null Primary Key, Keywords nvarchar(max))
Insert @Inputs(Id, Keywords) Values(1, 'cat, dog, man, mouse')
Insert @Inputs(Id, Keywords) Values(2, 'man, pen, pencil, eraser')
Insert @Inputs(Id, Keywords) Values(3, 'dog, man, friends')
Insert @Inputs(Id, Keywords) Values(4, 'dog, leash')
Declare @LCID int
Declare @StopListId int
Declare @AccentSensitive int
Set @LCID = Cast(DatabasePropertyEx('master','LCID') As int)
Set @StopListId = 0
Set @AccentSensitive = 1
Select S.display_term, Count(*) As Frequency
From @Inputs As I
Cross Apply (
Select display_term
From sys.dm_fts_parser(QUOTENAME(I.Keywords, '"')
, @LCID, @StopListId, @AccentSensitive)
) As S
Group By S.display_term
但是,如果您不使用SQL Server 2008,那麼您需要一個拆分函數。我在這篇文章的末尾介紹過。然後將查詢很簡單:
Select LTrim(RTrim(S.Value)), Count(*) As Frequency
From @Inputs As I
Cross Apply dbo.Split(I.Keywords, ',') As S
Group By LTrim(RTrim(S.Value))
和分割功能:
Create Function [dbo].[Split]
(
@DelimitedList nvarchar(max)
, @Delimiter varchar(2) = ','
)
RETURNS TABLE
AS
RETURN
(
With CorrectedList As
(
Select Case When Left(@DelimitedList, DataLength(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
+ @DelimitedList
+ Case When Right(@DelimitedList, DataLength(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
As List
, DataLength(@Delimiter) As DelimiterLen
)
, Numbers As
(
Select TOP (Coalesce(Len(@DelimitedList),1)) Row_Number() Over (Order By c1.object_id) As Value
From sys.objects As c1
Cross Join sys.columns As c2
)
Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
, Substring (
CL.List
, CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen
, CharIndex(@Delimiter, CL.list, N.Value + 1)
- (CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen)
) As Value
From CorrectedList As CL
Cross Join Numbers As N
Where N.Value < Len(CL.List)
And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
)
邊緣情況:該解決方案將虛報的比賽,如果一個字符串可以是另一個子串(如:'cat'是'locate'的子串)。 – 2011-04-08 11:52:37