Maintaining Database Consistency with Transactions 27 Jul 2005 00:00 GMT
While databases can efficiently hold large amounts of information that can be queried, all that data and all that querying
power is useless if the data is incorrect or nonsensical. Databases provide a plethora of techniques for ensuring the integrity and
consistency: primary key and unique constraints can be employed to ensure entity integrity; foreign key constraints aid in
ensuring relational integrity, and transactions help ensure that the database's data remains consistent.
While INSERT, UPDATE, and DELETE statements are the most
granular operations for modifying a database's underlying data, at times we want to treat multiple
INSERT, UPDATE, and/or DELETE statements as one atomic operation.
That is, in certain situations, rather than having each INSERT, UPDATE, and DELETE statement
stand on its own, we want the set of statements to be, together, an indivisible unit. When issuing this set of
statements we want either the entire set of statements to succeed, or all to fail - there should be no 'in-between' state.
The canonical transactional example is transferring money from one account to another. A money transfer account at a bank
requires two steps; if we want to transfer $500 from our checking account to our savings account, the following steps must be
processed:
- First, $500 must be deducted from our checking account,
- Next, $500 must be added to the savings account
In terms of SQL syntax, this would involve two UPDATE statements - one subtracting $500 from the balance of
the checking account and the other incrementing the savings account balance by $500. It is vital, however, that these two
steps are treated as one atomic unit. What we want to avoid is to have step 1 complete, subtracting $500 from our checking
account, but before step 2 can run, crediting our savings account, imagine that the database server crashes. (Well, this
scenario is something the bank might not get too upset over!) It is important that either both of these steps complete
in total or neither complete.
Database transactions are what ensure atomicity, one of the key features of any database system. Microsoft SQL Server, as
well as any professional grade database product, has support for transactions. In this article we'll examine how to wrap
multiple SQL statements within an atomic database transaction using the SqlTransaction class in the
System.Data.SqlClient namespace. Read on to learn more!
Read More >
Source: 4GuysFromRolla