我们有一个第三方应用程序,它接受使用 XML RPC 机制调用存储过程的调用。
我们使用这种机制发送一个包含多个表的 ZIP 压缩数据集,其中包含一堆更新/删除/插入。另一方面,CLR sproc 解压缩数据并获取数据集。
然后,执行以下代码:
using (var conn = new SqlConnection("context connection=true"))
{
if (conn.State == ConnectionState.Closed)
conn.Open();
try
{
foreach (DataTable table in ds.Tables)
{
string columnList = "";
for (int i = 0; i < table.Columns.Count; i++)
{
if (i == 0)
columnList = table.Columns[0].ColumnName;
else
columnList += "," + table.Columns[i].ColumnName;
}
var da = new SqlDataAdapter("SELECT " + columnList + " FROM " + table.TableName, conn);
var builder = new SqlCommandBuilder(da);
builder.ConflictOption = ConflictOption.OverwriteChanges;
da.RowUpdating += onUpdatingRow;
da.Update(ds, table.TableName);
}
}
catch (....)
{
.....
}
}
这是 RowUpdating 事件的事件处理程序:
public static void onUpdatingRow(object sender, SqlRowUpdatingEventArgs e)
{
if ((e.StatementType == StatementType.Update) && (e.Command == null))
{
e.Command = CreateUpdateCommand(e.Row, sender as SqlDataAdapter);
e.Status = UpdateStatus.Continue;
}
}
和 CreateUpdateCommand 方法:
private static SqlCommand CreateUpdateCommand(DataRow row, SqlDataAdapter da)
{
string whereClause = "";
string setClause = "";
SqlConnection conn = da.SelectCommand.Connection;
for (int i = 0; i < row.Table.Columns.Count; i++)
{
char quoted;
if ((row.Table.Columns[i].DataType == Type.GetType("System.String")) ||
(row.Table.Columns[i].DataType == Type.GetType("System.DateTime")))
quoted = '\'';
else
quoted = ' ';
string val = row[i].ToString();
if (row.Table.Columns[i].DataType == Type.GetType("System.Boolean"))
val = (bool)row[i] ? "1" : "0";
bool isPrimaryKey = false;
for (int j = 0; j < row.Table.PrimaryKey.Length; j++)
{
if (row.Table.PrimaryKey[j].ColumnName == row.Table.Columns[i].ColumnName)
{
if (whereClause != "")
whereClause += " AND ";
if (row[i] == DBNull.Value)
whereClause += row.Table.Columns[i].ColumnName + "=NULL";
else
whereClause += row.Table.Columns[i].ColumnName + "=" + quoted +
val + quoted;
isPrimaryKey = true;
break;
}
}
/* Only values for column that is not a primary key can be modified */
if (!isPrimaryKey)
{
if (setClause != "")
setClause += ", ";
if (row[i] == DBNull.Value)
setClause += row.Table.Columns[i].ColumnName + "=NULL";
else
setClause += row.Table.Columns[i].ColumnName + "=" + quoted +
val + quoted;
}
}
return new SqlCommand("UPDATE " + row.Table.TableName + " SET " + setClause + " WHERE " + whereClause, conn);
}
但是,当我们有很多记录时,这真的很慢。
有没有办法优化这个或完全不同的方式在几个表上发送大量 udpate/delete?我真的很想为此使用 TSQL,但无法找到将数据集发送到常规存储过程的方法。
补充笔记:
- 我们不能直接访问 SQLServer 数据库。
- 我们尝试不进行压缩,但速度较慢。