2010-02-22 77 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]