2011-11-15 112 views
1

有没有办法根据字数来创建搜索动态搜索?创建使用T-SQL存储过程

例如,如果我搜索carwheel它会创建T-SQL搜索类似

select * from table 
where 
    (word is like @word1) 
    and (word is like @word2) 

其中@ WORD1为car和@ WORD2是wheel

它可以是任何数量的单词,因此这应该是动态的。

谢谢。

回答

1

试试这个,@wordtable可以动态包含所有你想要的话。它只会从@table中找到所有单词存在的行:

declare @wordtable table(word varchar(20)) 
declare @table table(word varchar(500)) 

insert @wordtable values('car') 
insert @wordtable values('wheel') 

insert @table values('carwheel') 
insert @table values('car') 
insert @table values('wheel') 
insert @table values('wheelcat') 

select * from @table t 
where not exists (select 1 from @wordtable where t.word not like '%' + word + '%') 

“Contains”会精确地还是更好。但这是解决问题的一种体面的方式。

0

这将是非常缓慢,不可扩展。 你为什么不考虑使用类似Lucene的东西。

1

假设它确实是你要搜索的词,SQL Server内置全文搜索(http://msdn.microsoft.com/en-us/library/ms142571.aspx) - 它一直存在至少8年。它并不完美 - 你可以做一个案例Lucene的是更好 - 但如果你的需求很简单,它肯定不会工作。

这也意味着你可以只使用过的文本搜索,如“模糊”匹配的架子功能。

正如你不会有尽可能多的代码来写,你会避免在你的伪代码的bug -

(word is like @word1) 
    and (word is like @word2) 

只会产生一个结果,如果字词1和字词2是相同的......

0

我会把考虑什么上面已经说了,但是如果你仍想为此编写SQL,你可以尝试CHARINDEX函数

 
declare @searchTerms varchar(100) 
select @searchTerms = 'WORD1,WORD2,GIRLS,BOYS' -- some list 

select Field1, Field2 , Field3 , Field4 
from SomeTable 
where CHARINDEX(',' + Field1 + ',', ',' + @searchTerms + ',' , 0) > 0 

所以你searchTerms,表和F ield可以通过变量,如果你想更换,那么你建立一个SQL语句,你再执行