【问题标题】:how to remove the extra AND from the loop如何从循环中删除额外的 AND
【发布时间】:2013-01-10 18:36:45
【问题描述】:
foreach (string word in allTheseWords)
{
allTheseStringsWhereClause = allTheseStringsWhereClause + 
                             " report=" + 
                             word + 
                             " AND ";
}

问题是在循环之后,SQL 子句末尾多了一个AND

我该如何解决这个问题?

【问题讨论】:

标签: c# .net string


【解决方案1】:

您也可以使用LINQ

string _final = string.Join(" AND ", (allTheseWords.Select(x => "report=" + x)));

【讨论】:

  • 您使用了错误的变量。 allTheseStringsWhereClause 是一个字符串。单词在allTheseWords 变量中。
【解决方案2】:

通过将用户输入插入到 sql where 子句中,您将引入 SQL 注入攻击的向量。不要使用这种方法。基本上你想使用 SQL 参数。

where report in @allTheseWords

http://en.wikipedia.org/wiki/SQL_injection

编辑

请参阅Parameterize an SQL IN clause 中投票最多的答案,了解如何真正在查询中进行参数化。

【讨论】:

  • 问题是关于字符串操作,而不是 SQL 最佳实践。这不是对他问题的回答,最好是作为对问题的评论而不是答案。
  • @TimothyStrimple,我非常不同意。 OP 特别提到了allTheseStringsWhereClause,这意味着一个 SQL where 子句。这是错误,必须更正。
  • 呃。哪个数据库允许您将数组作为参数传递?
  • @RichardSchneider 如果 OP 所指的 WHERE 子句用于过滤数据集怎么办?无论如何,这仍然是 NOT 参数化 IN 子句的正确方法。
  • @Random832。抱歉,我只是采取简单的方法而不进行研究(我总是使用 ORM),这就是我说的基本原因)。但是现在在stackoverflow.com/questions/337704/… 中查看得票最多的答案
【解决方案3】:

这种问题很常见,这里就是证明。

  1. Delete last char of string
  2. How to delete last character in a string in C#?
  3. Finding the last index of an array

但这是我的简单解决方案

        string[] allTheseWords = { "try", "test", "let" };
        string whereLine = string.Empty;
        foreach (var item in allTheseWords)
                whereLine += "report = " + item.ToString() + " and ";
        string final = whereLine.Remove(whereLine.Length - 5);
        Console.WriteLine(final);
        Console.ReadLine();

【讨论】:

    【解决方案4】:

    一个简单的方法是添加一个虚假的 always-true 子句(并移动 AND):

    string allTheseStringsWhereClause = "WHERE 1=1";
    foreach (string word in allTheseWords)
    {
    allTheseStringsWhereClause = allTheseStringsWhereClause + 
                                 " AND report=" + 
                                 word;
    }
    

    【讨论】:

      【解决方案5】:

      您不需要 LINQ,只需使用 Join

      string whereClause = " report=" + String.Join(" AND report=", allTheseWords);
      

      【讨论】:

        【解决方案6】:

        无需对子字符串方法进行硬编码的最佳方法是尝试聚合 LINQ 查询

        var result = allTheseWords.Aggregate(allTheseStringsWhereClause, (current, word) => current + " report=" + word + " AND ");
        

        【讨论】:

          【解决方案7】:

          简单。您只需要执行 allTheseStringsWhereClause.substr(0,-4) 即可!

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-09-30
            • 2011-11-24
            • 2019-01-31
            • 1970-01-01
            • 2010-10-23
            • 2014-01-13
            • 2018-09-11
            • 1970-01-01
            相关资源
            最近更新 更多