SqlDataAdapter 优化 foreach

SqlDataAdapter optimize foreach

此 C# 代码经测试可正常工作,但对我来说效率不高。我怎样才能避免每次 foreach 交互中的所有开销,例如 1,000 行?

SqlConnection con = new SqlConnection(strConn);  // strConn is set elsewhere in the code
string strSQL = "select pkCustomer from Customer where YearEndDeactivateInd = 1";
SqlDataAdapter adap = new SqlDataAdapter(strSQL, con);
DataTable dt = new DataTable();
con.Open();
adap.Fill(dt);

foreach (DataRow row in dt.Rows)
{
    string strSQL1 = "update Ticket set activeInd = 0 where fkCustomer = " + row["pkCustomer"].ToString();
    SqlDataAdapter adap1 = new SqlDataAdapter(strSQL1, con);
    DataTable dt1 = new DataTable();
    adap1.Fill(dt1);
}

con.Close();

我正在根据另一个 table 的结果更新一个。我应该改用批量更新吗?

像这样使用查询

update Ticket
set activeInd = 0
where fkCustomer in (
    select pkCustomer
    from Customer
    where YearEndDeactivateInd = 1
)

不使用适配器

using (var con = new SqlConnection(strConn))
{
    string sql = "here query above";
    con.Open();

    using (var cmd = new SqlCommand(sql, con))
    {
        int rowsAffected = cmd.ExecuteNonQuery();
    }
}

您只需一次查询即可完成所有操作。

例如

UPDATE Ticket 
  SET activeInd = 0 
WHERE 
  fkCustomer IN 
    (SELECT pkCustomer 
     FROM Customer 
     WHERE YearEndDeactivateInd = 1
    )  

或者更好:

UPDATE T 
  SET activeInd = 0 
FROM 
  Ticket T 
  INNER JOIN Customer C 
    ON T.fkCustomer = C.pkCustomer 
WHERE 
  C.YearEndDeactivateInd = 1

无论哪种方式,SQL 本身都会更有效率。