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

问题描述 投票:-1回答:1

如何为参数列表生成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)
c# sql sql-server sqlcommand
1个回答
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,则无法使用此功能

© www.soinside.com 2019 - 2024. All rights reserved.