- I have SQL Server 2000, it doesn't support MultipleActiveResults.
- I have to do multiple inserts, and it's done with one connection per insertion.
- I want to begin a transaction before all insertions and finish it after all insertions.
- How do I do it?
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- Generic Generics in Managed C++
- How to Debug/Register a Permanent WMI Event Which
What is the reason you don't use one connection and multiple commands (actually one command recreated in loop)? Maybe this solution will work for you:
Also see
Sql Server Transactions - ADO.NET 2.0 - Commit and Rollback - Using Statement - IDisposable
I don't think a transaction can span multiple connections.
What's the reasoning for doing the multiple inserts in separate connections? I would think you'd want them in a single connection normally.
You didn't specify if you're using .NET 2.0, but I'll make that assumption. C# 3.0 sample code is listed below:
If any of the DB statements fail, the ts.complete will never be reached and the transaction will be rolled back automatically at the end of the using statement. However, one caveat to this approach is that you'll end up leveraging the DTC if you use multiple connections, which means slower performance.
Edited to change SqlTransaction to TransactionScope
An example of forcing a single SQL connection to avoid using the DTC:
Transactions are created on a connection and have no scope beyond the connection they are created on so you can't do what you are asking. Refactor so that you can execute the inserts sequentially on a connection rather than simultaneously or implement a different mechanism to achieve rollback (e.g. a table of inserted keys that can be used as a look up to delete inserted records if an error is encountered later in the process)