问题
We're looking to implement a Search query that will do a full-text search on a specific column in SQL. We're open to do it in SQL directly or in C# as suggested by TomC below. The query will be entered by users like -
(A AND B) OR (C AND D)
We want to convert this search text into SQL query as below -
WHERE (col LIKE '%A%' AND col LIKE '%B%') OR (col LIKE '%C%' AND col LIKE '%D%')
Please advise what would be the best approach to handle this.
回答1:
I do not know if this is the best regex replace, but it works
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication58
{
class Program
{
static void Main(string[] args)
{
string pattern = @"(?'prefix'[^\w]+)?(?'var1'\w+)(?'operator'\s+(AND|OR)\s+)(?'var2'\w+)(?'suffix'.*)?";
string input = "(A AND B) OR (C AND D)";
Match match = null;
do
{
match = Regex.Match(input, pattern);
if (match.Success) input = Regex.Replace(input, pattern, ReplaceVars(match));
} while (match.Success);
}
public static string ReplaceVars(Match m)
{
return m.Groups["prefix"] + "col LIKE %'" + m.Groups["var1"].Value + "'" + m.Groups["operator"] + "col LIKE %'" + m.Groups["var2"].Value + "'" + m.Groups["suffix"];
}
}
}
回答2:
On the database side, I would use CONTAINS if you are looking for fuzzy or less precise matches. I mention this in case you made the original post simplistic. Unlike LIKE with a leading wild card, it can use an INDEX which would make it faster. Using LIKE in this fashion would result in a table scan. You will have to create the FULLTEXT INDEX to use CONTAINS.
Another approach would be to use CHARINDEX. This can use an index, but isn't guaranteed to. I'd test this compared to LIKE in your environment.
where
(charindex('A',col) > 0 and charindex('B',col) > 0)
or (charindex('C',col) > 0 and charindex('D',col) > 0)
来源:https://stackoverflow.com/questions/51608427/convert-boolean-text-search-into-sql-query-where-clause