开发者

Using "LIKE" in a SQL statement to query for words in a sentence regardless of the order

Would like to know how I can use LIKE in a SQL statement so tha开发者_运维百科t it returns the words in the sentence that I typed in my search textbox regardless of the order in which they are typed.

This is the code i use and it only works if the words are in order

StringBuilder mystringBuilder = new StringBuilder(strSearch);
mystringBuilder.Replace(" ", "%"); 

QueryClause q = new QueryClause("AND", "IssueDescription", "LIKE", "%" + strSearch + "%", SqlDbType.VarChar, false); 
colQueryClauses.Add(q); 

q = new QueryClause("OR", "IssueTitle", "LIKE", "%" + mystringBuilder + "%", SqlDbType.VarChar, false); 
colQueryClauses.Add(q); 


If you have Word1 and Word2 in your textbox you can split them and use like below.

SELECT * FROM Table WHERE Column LIKE '%Word1%' AND Column LIKE '%Word2%'

But you'd better define a full text search and use CONTAINS to query.


If you want to search for multiple words you can use something like:

SELECT
  *
FROM
  table
WHERE
   (Column LIKE '%word1%') OR
   (Column LIKE '%word2%') OR
   (Column LIKE '%word3%')

You can change OR for AND if you want to get the column that contains ALL the words instead of ANY

But is still not very useful because you have to know before hand how many words you are going to use as argument.

Maybe you should use Full-Text search feature from SQL Server link


You can search for the word "foo" in column "bar" by using:

WHERE Bar LIKE '%foo%'

Is that what you're looking for? If not, can you give an example?

Hope that helps,

John


SELECT    some_field
FROM      some_table
WHERE     some_field
  LIKE    '%first_value%'
  OR      some_field
  LIKE    '%second_value%'
  ...


In C#, split your search sentence into words (using space character as a separator). Then create a string that will be your WHERE clause like this:

"WHERE searchColumn LIKE '% " + splitString[0] + " %' AND searchColumn LIKE '% " + splitString[1] + " %'"

and so on. Use a for loop. Concat the WHERE clause with rest of the SQL query and execute.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜