批量更新数据(BatchUpdate)
/// <summary> /// 批量更新数据,注意:如果有timestamp列,要移除 /// </summary> /// <param name="sourceTable">源数据</param> /// <param name="targetTableName">目标table</param> /// <param name="primaryKeyName">主键,根据主键来更新数据,不是自增长</param> /// <param name="identity">自增长列</param> /// <param name="columnsName">列名</param> /// <param name="limitWhere">条件</param> /// <param name="batchNum">批量更新的数量</param> /// <returns></returns> public Boolean BatchUpdate(DataTable sourceTable, string targetTableName, string primaryKeyName, string identity, string[] columnsName, string limitWhere, int batchNum) { if (string.IsNullOrEmpty(targetTableName)) return false; if (string.IsNullOrEmpty(primaryKeyName)) return false; if (columnsName == null || columnsName.Length <= 0) return false;
DataSet ds = new DataSet();
ds.Tables.Add(sourceTable);
ds.Tables[].TableName = targetTableName; using (SqlConnection conn = new SqlConnection(strConn))
{
conn.Open(); using (SqlTransaction transaction = conn.BeginTransaction(IsolationLevel.ReadCommitted))//使用加强读写锁事务,避免脏读
{ try
{ foreach (DataRow row in ds.Tables[].Rows)
{
row.AcceptChanges();
row.SetModified();//所有行设置为可修改
} string cols = string.Join(",", columnsName);
cols = "[" + cols.Replace(",", "],[") + "]";
SqlCommand cmd = new SqlCommand(string.Format("SELECT {2} FROM {0} WHERE {1}", targetTableName, limitWhere, cols), conn);
cmd.Transaction = transaction;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
SqlCommandBuilder sqlCmdBuilder = new SqlCommandBuilder(adapter);
adapter.AcceptChangesDuringFill = false;
adapter.Fill(ds); string updateSQL = string.Empty;
SqlParameter[] paras = new SqlParameter[columnsName.Length]; for (int i = ; i < columnsName.Length; i++)
{ //去除自增长ID ,根据可控的自增Id进行更新 if (columnsName[i] != primaryKeyName && columnsName[i] != identity)
{
updateSQL += ("[" + columnsName[i] + "]" + "=@" + columnsName[i] + ",");
} if (sourceTable.Columns[i].DataType.Name == "Int32")
{
paras[i] = new SqlParameter("@" + columnsName[i], SqlDbType.Int, , columnsName[i]);
} else if (sourceTable.Columns[i].DataType.Name == "DateTime")
{
paras[i] = new SqlParameter("@" + columnsName[i], SqlDbType.DateTime, , columnsName[i]);
} else if (sourceTable.Columns[i].DataType.Name == "Double")
{
paras[i] = new SqlParameter("@" + columnsName[i], SqlDbType.Decimal, , columnsName[i]);
} else
{
paras[i] = new SqlParameter("@" + columnsName[i], SqlDbType.NVarChar, -, columnsName[i]);//-1表示大于4000的长度
}
} if (!string.IsNullOrEmpty(updateSQL))
{
updateSQL = updateSQL.Trim(',');
} string limitSql = ("[" + primaryKeyName + "]" + "=@" + primaryKeyName);
SqlCommand updateCmd = new SqlCommand(string.Format("UPDATE {0} SET {1} WHERE {2}", targetTableName, updateSQL, limitSql)); //设置不修改源Table
updateCmd.UpdatedRowSource = UpdateRowSource.None;
adapter.UpdateCommand = updateCmd;
adapter.UpdateCommand.Parameters.AddRange(paras);
updateCmd.Transaction = transaction;
adapter.UpdateCommand.CommandTimeout = ;//超时时间
adapter.UpdateBatchSize = batchNum;
adapter.Update(ds, targetTableName);
ds.AcceptChanges();
transaction.Commit(); return true;
} catch (Exception ex)
{
transaction.Rollback(); return false; throw ex;
} finally
{
conn.Close();
conn.Dispose();
}
}
}
}