Sql-server – Distributed – across multiple databases or servers – Transactions

rollbacksql serversql-server-2008-r2transaction

I have some doubts related to transactions in SQL. I perform below steps.

  1. Connection 1 open for DB1 database
  2. Begin transaction for Connection 1
  3. Run the commands on Connection 1
  4. Connection 2 open for DB2 database
  5. Begin transaction for Connection 2
  6. Run the commands on Connection 2
  7. Commit transaction for Connection 2
  8. Commit transaction for Connection 1

If commit transaction on Connection 1 fails(rollback) then transaction on connection 2 should rollback.
Is it possible? How it can be done?

Best Answer

Yes this can be done but you need a third party acting as a transaction coordinator. The standard protocol for this is called Two Phase Commit (2PC). This is usually done with a transaction manager acting as the coordinator.

This can also be generalized further to more than two databases. In fact it doesn't even have to be databases as the approach is generally applied to "transactional resources". Besides databases the other common transactional resource is a message queue. The usual example is to perform some work in a database (ex: update an account balance) and also send a message out on a message queue (ex: an outbound order).

For this to work your datasources need to support 2PC, usually via the XA protocol. How to do it depends on the specific type of datasource and programming language (ex: for Java you'd use an XADataSource).