在进行实际插入之前测试 tsql 插入?
Test tsql inserts before doing actual inserts?
我有一个 asp.net 应用程序可以插入到多个 tsql 表中。格式如下:
Car myCar = new Car();
myCar.InsertNewCar(); //Makes SP call usp_InsertCar()
Truck myTruck = new Truck();
myTruck.InsertNewTruck(); //Makes SP call usp_InsertTruck()
Customer myCustomer = new Customer();
myCustomer.InsertNewCustomers(); //Makes SP call usp_InsertCustomers()
这些方法中的每一个都有一个 try...catch 异常。问题是它可能会在 myCustomer.InsertNewCustomers()
中断,但之前的 2 个插入已经完成。然后我必须手动删除所有插入,然后重试。我们已经进行了数据检查,但仍然会发生这种情况。
我正在考虑对这些存储过程中的每一个使用 COMMIT 和 ROLLBACK,因此第一遍将调用所有 5 个回滚事务的方法。如果一切正常,那么我将使用 COMMIT 调用相同的存储过程。这样我就可以确定插入的内容是正确的。
这有意义吗?
您可以通过 C# 代码管理交易。添加一个 using (TransactionScope scope = new TransactionScope())
块来包装您的调用。我认为您可能需要为此使用相同的连接 - 因此您可能必须将连接对象作为参数传递给您的方法。
编辑: 只是为了添加更多细节....
using (TransactionScope scope = new TransactionScope())
{
// Assuming you are using SQL Server....
using (SqlConnection conn = new SqlConnection(connectString1))
{
conn.Open();
InsertToTable1(conn);
// Snip...
InsertToTable5(conn);
// If this point is reached, everything is tickety boo
// Commit the transaction using Complete.
// If the scope.Complete line is not hit before the using block
// is exited (i.e. an Exception is thrown, the transaction is rolled
// back.
scope.Complete();
}
}
您的 InsertIntoTable
方法将类似于
public void InsertIntoTable1(SqlConnection conn)
{
// Some non-database code could be here....
SqlCommand cmd = conn.CreateCommand();
// Configure command and execute
// Some non-database code could also be here....
}
我有一个 asp.net 应用程序可以插入到多个 tsql 表中。格式如下:
Car myCar = new Car();
myCar.InsertNewCar(); //Makes SP call usp_InsertCar()
Truck myTruck = new Truck();
myTruck.InsertNewTruck(); //Makes SP call usp_InsertTruck()
Customer myCustomer = new Customer();
myCustomer.InsertNewCustomers(); //Makes SP call usp_InsertCustomers()
这些方法中的每一个都有一个 try...catch 异常。问题是它可能会在 myCustomer.InsertNewCustomers()
中断,但之前的 2 个插入已经完成。然后我必须手动删除所有插入,然后重试。我们已经进行了数据检查,但仍然会发生这种情况。
我正在考虑对这些存储过程中的每一个使用 COMMIT 和 ROLLBACK,因此第一遍将调用所有 5 个回滚事务的方法。如果一切正常,那么我将使用 COMMIT 调用相同的存储过程。这样我就可以确定插入的内容是正确的。
这有意义吗?
您可以通过 C# 代码管理交易。添加一个 using (TransactionScope scope = new TransactionScope())
块来包装您的调用。我认为您可能需要为此使用相同的连接 - 因此您可能必须将连接对象作为参数传递给您的方法。
编辑: 只是为了添加更多细节....
using (TransactionScope scope = new TransactionScope())
{
// Assuming you are using SQL Server....
using (SqlConnection conn = new SqlConnection(connectString1))
{
conn.Open();
InsertToTable1(conn);
// Snip...
InsertToTable5(conn);
// If this point is reached, everything is tickety boo
// Commit the transaction using Complete.
// If the scope.Complete line is not hit before the using block
// is exited (i.e. an Exception is thrown, the transaction is rolled
// back.
scope.Complete();
}
}
您的 InsertIntoTable
方法将类似于
public void InsertIntoTable1(SqlConnection conn)
{
// Some non-database code could be here....
SqlCommand cmd = conn.CreateCommand();
// Configure command and execute
// Some non-database code could also be here....
}