我们希望实现一个搜索查询,它将在SQL中的特定列上执行全文搜索。我们可以直接在SQL
中完成,也可以像下面TomC所建议的那样在C#
中完成。查询将由用户输入,例如-
(A AND B) OR (C AND D)
我们希望将此搜索文本转换为SQL查询,如下所示-
WHERE (col LIKE '%A%' AND col LIKE '%B%') OR (col LIKE '%C%' AND col LIKE '%D%')
请告诉我处理这个问题的最佳方法是什么。
发布于 2018-07-31 17:51:17
我不知道这是否是最好的正则表达式替代,但它可以工作
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"];
}
}
}
发布于 2018-08-01 05:12:00
在数据库方面,如果您正在寻找模糊或不太精确的匹配,我将使用CONTAINS
。我提到这一点是为了防止你把最初的帖子简单化。与具有领先通配符的LIKE
不同,它可以使用INDEX
,这将使其速度更快。以这种方式使用LIKE
将导致表扫描。您必须创建FULLTEXT INDEX
才能使用CONTAINS
。
另一种方法是使用CHARINDEX
。这可以使用索引,但不能保证使用索引。我会在您的环境中将其与LIKE
进行比较。
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
复制相似问题