简体   繁体   English

从字符串列表构建查询

[英]Building a Query From a List of Strings

How would you take an arbitrary list of strings (of the form "%[text]%") and a database column, and turn them into a SQL query that does a LIKE comparison for each string in the list? 您将如何获取任意字符串列表(形式为“%[text]%”)和数据库列,并将其转换为对列表中的每个字符串进行LIKE比较的SQL查询?

An example: I have three strings in my list, "%bc%", "%def%" and "%ab%". 一个例子:我的列表中有三个字符串,分别是“%bc%”,“%def%”和“%ab%”。 This builds the query: 这将建立查询:

([ColumnName] LIKE "%bc" AND [ColumnName] LIKE "%def%") AND [ColumnName] LIKE "%ab%"

AC# example would be excellent, but feel free to write it in the language of your choice. AC#示例将是一个很好的示例,但是可以用您选择的语言编写它。

To answer your question directly, 要直接回答您的问题,

string.join(" and ", 
    (new[] { "%bc%", "%def%", "%ab%" })
    .Select(x => string.Format("[{0}] LIKE '{1}'",columnName, x))
    .ToArray());

To solve your problem, you should use the Sql Server full-text search tools. 要解决您的问题,您应该使用Sql Server全文搜索工具。 the query would be: 查询将是:

select * from table
where FREETEXT("bc def ab")

With the correct indices, this should outperform a list of LIKEs 使用正确的索引,这应该胜过LIKE列表

It's just a string join on a map: 这只是地图上的字符串连接:

>>> los=['ab', 'cd', 'ef']
>>> ' and '.join(("somecolumn like '%%%s%%'" % s) for s in los)
"somecolumn like '%ab%' and somecolumn like '%cd%' and somecolumn like '%ef%'"

or 要么

>>> ' and '.join(("somecolumn like '%" + s + "%'") for s in los)
"somecolumn like '%ab%' and somecolumn like '%cd%' and somecolumn like '%ef%'"

I'd use a StringBuilder and a for loop. 我会使用StringBuilder和for循环。 Assuming your list is called "list" and is a List: 假设您的列表称为“列表”,并且是一个列表:


StringBuilder sql = new StringBuilder();
if (list.Count > 0)
    sql.AppendFormat(CultureInfo.InvariantCulture, "([{0}] LIKE \"{1}\"", columnName, list[0]);

for (int i = 1; i < list.Count; i++)
{
    sql.AppendFormat(CultureInfo.InvariantCulture, " AND [{0}] LIKE \"{1}\"", columnName, list[i]);
}

if (list.Count > 0)
    sql.Append(")");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM