返回包含字符串中所有单词的行

时间:2012-06-29 18:40:29

标签: sql-server sql-server-2008

我想要检索所有行,其中某列包含字符串参数中传递的所有单词,无论它们出现的顺序如何。

如果参数为'hi abc',那么我想要这一行:abc def hijk而不是hijk lmnop qr

我设法做到了,但我怀疑它不是很好,所以我想看看其他选择。如何更好地完成下面的代码呢?

create table t (s varchar(200));
insert into t (s) values
('abc def hijk'),
('hijk lmnop qr'),
('stu'),
('v xyz')
;

create function dbo.matchRows (@string varchar(max))
returns varchar(max)
begin

    set @string = replace(@string, '''', '''''');
    set @string = replace(@string, '  ', ' ');
    set @string = replace(@string, '  ', ' ');
    set @string = replace(@string, ' ', '%'' and s like ''%');
    set @string = 's like ''%' + @string + '%''';
    set @string = 'select * from t where ' + @string;
    return @string;

end;

declare @query varchar(max);
set @query = (select dbo.matchRows('hi abc'));
execute (@query);

1 个答案:

答案 0 :(得分:4)

这样的事情应该有效。它将您的搜索参数转换为XML,然后将其拆分为表变量。之后,它会在您的@t表中搜索您传入的所有拆分参数(其中找到的单词的数量等于搜索参数的数量,使其与所有这些参数匹配)。

DECLARE @SearchStringParams varchar(max),
  @Split char(1),
  @Xml xml,
  @NumOfSearchTerms Int
DECLARE @SplitTable table (valToSearchFor varchar(100));

SELECT @SearchStringParams = 'hi,abc',
@Split = ','

SELECT @Xml = CONVERT(xml,'<root><s>' + REPLACE(@SearchStringParams,@Split,'</s><s>') + '</s></root>')

INSERT @SplitTable
SELECT [Value] = T.c.value('.','varchar(20)')
FROM @Xml.nodes('/root/s') T(c)

SELECT @NumOfSearchTerms = @@ROWCOUNT

DECLARE @t table (searchWords varchar(200));
insert into @t (searchWords) values
('abc def hijk'),
('hijk lmnop qr'),
('stu'),
('v xyz')
;
select t.searchWords
from @t t inner join @SplitTable s
on t.searchWords like ('%' + s.valToSearchFor + '%')
group by t.searchWords
having count(t.searchWords) = @NumOfSearchTerms