在单个事务范围内多次调用相同的 ADO.NET 命令
calling the same ADO.NET Command several times within the scope of a single transaction
我的问题涉及如何在一个订单中插入多个行项目,例如,在单个交易的范围内。
必须插入所有行项目,否则必须回滚事务。
是否可以在不发送自定义 CLR 对象作为参数(相当于 table 值参数)的情况下对同一个 table 进行多次插入?是否可以在循环内调用 MyInsertSingleLineItemCommand,在每次调用时插入一个订单项?我们需要临时中介吗table?
Can multiple inserts to the same table be done without sending a
custom CLR object as a parameter, equivalent to a table-valued
parameter?
是的,您可以使用 SqlTransaction.
在单个事务中逐行执行
Can MyInsertSingleLineItemCommand be called inside a loop, inserting
one line item with each invocation?
是下面的示例代码。
using (SqlConnection cn = new SqlConnection("YOUR CONNECTION STRING")
{
cn.Open();
using (SqlTransaction tr = cn.BeginTransaction())
{
// your looping code here persisting to sql server db
tr.Commit();
}
}
您也可以使用 TransactionScope 来完成此操作。
using (var ts = new TransactionScope())
{
using (SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING"))
{
connection.Open();
// your looping code here persisting to sql server db
}
ts.Complete();
}
Do we need an intermediary temporary table?
不,你不需要临时 table。
话虽如此,您可能要考虑使用 SqlBulkCopy or a Table Value Parameter 将您的数据传递到 Sql 服务器。虽然这取决于您的要求。
我的问题涉及如何在一个订单中插入多个行项目,例如,在单个交易的范围内。
必须插入所有行项目,否则必须回滚事务。
是否可以在不发送自定义 CLR 对象作为参数(相当于 table 值参数)的情况下对同一个 table 进行多次插入?是否可以在循环内调用 MyInsertSingleLineItemCommand,在每次调用时插入一个订单项?我们需要临时中介吗table?
Can multiple inserts to the same table be done without sending a custom CLR object as a parameter, equivalent to a table-valued parameter?
是的,您可以使用 SqlTransaction.
在单个事务中逐行执行Can MyInsertSingleLineItemCommand be called inside a loop, inserting one line item with each invocation?
是下面的示例代码。
using (SqlConnection cn = new SqlConnection("YOUR CONNECTION STRING")
{
cn.Open();
using (SqlTransaction tr = cn.BeginTransaction())
{
// your looping code here persisting to sql server db
tr.Commit();
}
}
您也可以使用 TransactionScope 来完成此操作。
using (var ts = new TransactionScope())
{
using (SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING"))
{
connection.Open();
// your looping code here persisting to sql server db
}
ts.Complete();
}
Do we need an intermediary temporary table?
不,你不需要临时 table。
话虽如此,您可能要考虑使用 SqlBulkCopy or a Table Value Parameter 将您的数据传递到 Sql 服务器。虽然这取决于您的要求。