How to perform batch update in Sql through C# code

后端 未结 4 558
北恋
北恋 2020-12-29 09:39

I want to update multiple rows like below

update mytable set s_id = {0} where id = {1}

(Here s_id is evaluated based on some

4条回答
  •  不知归路
    2020-12-29 10:07

    Use a StringBuilder (System.Text.StringBuilder) to build your Sql, such as:

    StringBuilder sql = new StringBuilder();
    int batchSize = 10;
    int currentBatchCount = 0;
    SqlCommand cmd = null; // The SqlCommand object to use for executing the sql.
    for(int i = 0; i < numberOfUpdatesToMake; i++)
    {
      int sid = 0; // Set the s_id here
      int id = 0; // Set id here
      sql.AppendFormat("update mytable set s_id = {0} where id = {1}; ", sid, id);
    
      currentBatchCount++;
      if (currentBatchCount >= batchSize)
      {
        cmd.CommandText = sql.ToString();
        cmd.ExecuteNonQuery();
        sql = new StringBuilder();
        currentBatchCount = 0;
      }
    }
    

提交回复
热议问题