用于值列表的C#/ SQL重用参数

时间:2018-09-12 09:38:44

标签: c# sql sql-server sqlcommand

如何为参数列表生成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)

1 个答案:

答案 0 :(得分:0)

我找不到最初请求的解决方案,但表值参数(TVP)适合我的情况。
感谢@JeroenMostert提醒TVP

我不得不重做查询,并将子句从WHERE移到INNER JOIN部分中
SELECT * FROM T INNER JOIN @TVP TVP ON TVP.col1 = T.col1 AND TVP.col2 = T.col2

如果您不允许在数据库中创建TVP,则此方法将无效