【问题标题】:C#/SQL Reusing parameter for list of values值列表的 C#/SQL 重用参数
【发布时间】:2018-09-12 09:38:43
【问题描述】:

如何为参数列表生成 SqlCommand?
如何使用新的 OR 子句正确重用相同的参数?

public class InputList
{
    public string col1 { get; set; }
    public string col2 { get; set; }
}

public void Exec(IList<InputList> list)
{
   try
   {
       using (var conn = new SqlConnection(Settings.Default.DBConnStr))
       using (var cmd = conn.CreateCommand())
       {
           conn.Open();
           cmd.CommandType = CommandType.Text;

           // want to use SqlParameter to prevent sql injection
           var clause = list
                           .Select(x => $"(col1 = {x.col1} AND col2 = {x.col2}) OR ")
                           .Aggregate((curr, next) => curr + " " + next);
           // TODO: remove trainling OR

           cmd.CommandText =
               $@"SELECT *
                  FROM T
                  WHERE {clause}";

           // TODO: execute reader
        }
   }
   catch()
}

我必须迭代对象列表来编译 WHERE 子句

SELECT *
FROM T
WHERE
(col1 = @col1 AND col2 = @col2) OR
(col1 = @col1 AND col2 = @col2) OR
...
(col1 = @col1 AND col2 = @col2)

【问题讨论】:

  • 您能详细说明这个问题吗?在您的情况下,参数列表是什么?哪些参与过滤(问题中的查询没有很好的过滤器)等。
  • 对于多个值,通常最好将数据粘贴在表值参数中,这样可以完全避免动态 SQL。
  • @JeroenMostert,谢谢,我会坚持这个选项

标签: c# sql sql-server sqlcommand


【解决方案1】:

我无法为我的初始请求找到解决方案,但表值参数 (TVP) 非常适合我的情况。
感谢@JeroenMostert 提醒TVP

我不得不修改我的查询并将子句从 WHERE 移动到 INNER JOIN 部分
SELECT * FROM T INNER JOIN @TVP TVP ON TVP.col1 = T.col1 AND TVP.col2 = T.col2

如果不允许在数据库中创建 TVP,这将不起作用

【讨论】:

    猜你喜欢
    • 2021-11-10
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 2013-03-03
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    相关资源
    最近更新 更多