尝试通过SqlDataAdapter.Update(DataTable)
. 根据http://msdn.microsoft.com/en-us/library/system.data.statementtype(v=vs.100).aspx,可能的枚举值是 Select、Insert、Update、Delete 和 Batch,以及我猜 Batch 的值是 4。
我不太确定这个值是如何设置的,因为它属于我在 SqlRowUpdatedEventHandler 中获取的 SqlRowUpdatedEventArgs 对象,或者它为什么无效。
基本上,我正在从 Web 服务调用返回的 XmlNode 构建一个 DataTable,对数据视图进行排序,然后分批发布 200 个更新。
XmlNode result = null;
using (LeadService.ClientService service = new LeadService.ClientService())
{
const string UserName = "SomeUserName";
const string Password = "SomePassword";
const int ChildReportId = 746;
result = service.GetReportResults(UserName, Password, ChildReportId, null);
}
if (result.InnerXml != "")
{
DataTable leads = new DataTable();
leads.Columns.Add("ID1", typeof(int));
leads.Columns.Add("ID2", typeof(string));
leads.Columns.Add("CREATEDDATE", typeof(DateTime));
foreach (XmlNode n in result.ChildNodes)
{
DataRow row = leads.NewRow();
row["ID1"] = n["Id1"].InnerText;
row["ID2"] = n["Id2"].InnerText;
row["CREATEDDATE"] = n["DateAdded"].InnerText;
leads.Rows.Add(row);
}
leads.DefaultView.Sort = "CREATEDDATE";
DataTable newTable = leads.DefaultView.ToTable();
newTable.AcceptChanges();
foreach (DataRow r in newTable.Rows)
{
r.SetModified();
}
const string Update = "UPDATE SOMETHING SET ID1 = @ID1 WHERE ID2 = @ID2";
using (SqlConnection con = new SqlConnection(Dal.GetConnectionString("CONNECTIONSTRING")))
{
SqlDataAdapter adap = new SqlDataAdapter();
adap.UpdateCommand = new SqlCommand(Update);
adap.UpdateCommand.Parameters.Add("@ID1", SqlDbType.NVarChar, 75, "ID1");
adap.UpdateCommand.Parameters.Add("@ID2", SqlDbType.VarChar, 18, "ID2");
adap.UpdateCommand.UpdatedRowSource = UpdateRowSource.None;
adap.UpdateBatchSize = 200;
adap.RowUpdated += new SqlRowUpdatedEventHandler(adap_RowUpdated);
adap.Update(newTable);
}
}
这是事件处理程序:
private static void adap_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
{
_rowsProcessed += e.RowCount;
_recordsAffected += e.RecordsAffected;
}