2010-02-22 29 views
2

如何查询具有来自用户的某些文本输入的记录?用于搜索具有特定文本的记录的SQL查询?

例如在我的表适配器功能:

SELECT Word, Description, Example 
FROM WordLists 
WHERE (Word LIKE @SearchKey OR Description LIKE @SearchKey OR Example LIKE @SearchKey) 

有某些输入确切文本显然只记录会从数据库中获得。我需要做的是获取包含用户输入文本的所有记录。

回答

7
SELECT Word, Description, Example 
FROM WordLists 
WHERE ((Word LIKE '%' + @SearchKey + '%') 
    OR (Description LIKE '%' + @SearchKey + '%') 
    OR (Example LIKE '%' + @SearchKey +'%')) 
+0

感谢爵士阳光...... – hisoka21

1

另一种选择是:

SELECT Word, Description, Example 
FROM WordLists 
WHERE (Word || ' ' || Description || ' ' || Example) LIKE ('%' + @SearchKey + '%') 

这可能(也可能不会)更有效,而且可能产生一些误判,其中@SearchKey比赛Word || ' ' || Description,这可能是一件好事,它可能不;但根据您的特定风格,它可能会更具可读性。

+0

''||,寿”它类似于''||,是不是'或',而是SQL连接运算符。 –

+0

谢谢你,威廉姆爵士...... – hisoka21

1

根据您的数据集的大小,您可能想尝试全文(如果这是一个选项)。

您可以在所有3个可搜索列中创建全文索引,如果需要,也可以让您查询特定的一个(或多个)组合。您只需要在[Description]中存在搜索文本的行。

if object_id('dbo.ft_example') is not null drop table dbo.ft_example; 

create table dbo.ft_example (
    rowid int identity not null constraint pk_ft_example primary key, 
    [Word] varchar(100), 
    [Description] varchar(1000), 
    [Example] varchar(500) 
    ); 

insert dbo.ft_example ([Word], [Description], [Example]) 
select 'blah blah cat', 'blah blah blah blah blah blah blah blah bird', 'blah blah blah blah fish' union all 
select 'blah blah dog', 'blah blah blah blah blah blah blah blah cat', 'blah blah blah blah horse' union all 
select 'blah blah camel', 'blah blah blah blah blah blah blah blah squid', 'blah blah blah blah horse' union all 
select 'blah blah horse', 'blah blah blah blah blah blah blah blah cat', 'blah blah blah blah moose' union all 
select 'blah blah fish', 'blah blah blah blah blah blah blah blah whale', 'blah blah blah blah bird' union all 
select 'blah blah camel', 'blah blah blah blah blah blah blah blah squirel', 'blah blah blah blah kiwi' union all 
select 'blah blah kiwi', 'blah blah blah blah blah blah blah blah bird', 'blah blah blah blah horse'; 

if exists( 
    select * 
    from sys.fulltext_indexes 
    join sys.tables 
    on sys.tables.object_id = sys.fulltext_indexes.object_id 
    where sys.tables.name = 'ft_example' 
    ) 
    drop fulltext index on ft_example; 
go 
if exists (select * from dbo.sysfulltextcatalogs where name = 'example_ft_cat') 
    drop fulltext catalog example_ft_cat; 
go 

create fulltext catalog example_ft_cat; 
create fulltext index on dbo.ft_example ([Word], [Description], [Example]) 
    key index pk_ft_example on example_ft_cat; 
go 

select * 
from dbo.ft_example a 
join containstable(ft_example, ([Word], [Description], [Example]), 'bird') b 
     on a.rowid = b.[key]