如何查询具有用户特定文本输入的记录?
例如在我的表适配器函数中:
SELECT Word, Description, Example
FROM WordLists
WHERE (Word LIKE @SearchKey OR Description LIKE @SearchKey OR Example LIKE @SearchKey)
显然,只有具有某些输入的确切文本的记录才会从数据库中获取。我需要做的是获取包含用户输入文本的所有记录。
答案 0 :(得分:7)
SELECT Word, Description, Example
FROM WordLists
WHERE ( (Word LIKE '%' + @SearchKey + '%')
OR (Description LIKE '%' + @SearchKey + '%')
OR (Example LIKE '%' + @SearchKey +'%') )
答案 1 :(得分:1)
另一种选择是:
SELECT Word, Description, Example
FROM WordLists
WHERE ( Word || ' ' || Description || ' ' || Example ) LIKE ( '%' + @SearchKey + '%' )
这可能(或可能不)更高效,并且在@SearchKey
匹配Word || ' ' || Description
时可能产生一些误报,这可能是好事,也可能不是;但根据你的特殊风格,它可能会更具可读性。
答案 2 :(得分:1)
根据数据集的大小,您可能需要尝试全文(如果这是一个选项)。
您可以在所有3个可搜索列中创建全文索引,这样您还可以在需要时查询特定的(或组合) - 例如您想要只在[描述]中存在搜索文本的行。
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]