The rules to follow are grouped under the acronym ACID:
Before creating a transaction, you must define the operations that will be performed. To specify the beginning of the transaction, before the first operation, type BEGIN TRAN or BEGIN TRANSACTION with the following formula: BEGIN { TRAN | TRANSACTION } [ { transaction_name | @tran_name_variable } [ WITH MARK [ 'description' ] ] ] [ ; ] Start with either BEGIN TRAN or BEGIN TRANSACTION. After this, a transaction_name is optional. If you had previously declared a text-based variable (char, nchar, varchar, or nvarchar), and assigned the transaction name to it, you can omit the transaction_name and use the name of that variable instead. If you want the transaction to be described in a log file, type WITH MARK and provide a description that will be written to the file. The code between the BEGIN TRAN or BEGIN TRANSACTION line is part of the transaction.
After defining the operations that are part of the transaction, the database engine would execute them in the sequence they are written. You must indicate where this series of transactions ends. To do this, type the COMMIT TRAN or COMMIT TRANSACTION expression: BEGIN TRAN Name or BEGIN TRANSACTION Name Operations COMMIT TRAN Name or COMMIT TRANSACTION Name Consider the following example: USE Exercise; Go CREATE TABLE Employees ( EmployeeNumber nchar(10), EmployeeName nvarchar(50), DateHired date, HourlySalary money ); GO INSERT INTO Employees VALUES(N'593705', N'Frank Somah', N'20061004', 26.15), (N'720947', N'Paul Handsome', N'20000802', 36.05); GO INSERT INTO Employees(EmployeeName, EmployeeNumber, DateHired) VALUES(N'Clarice Simms', N'971403', N'20011112'); GO BEGIN TRANSACTION AddEmployees INSERT INTO Employees VALUES(N'595002', N'John Meah', N'20000212', 32.25), (N'928375', N'Chuck Stansil', N'20080628'), (N'792764', N'Orlando Perez', N'20000616', 12.95); COMMIT TRANSACTION AddEmployees; GO INSERT INTO Employees(EmployeeName, EmployeeNumber, HourlySalary, DateHired) VALUES(N'Gina Palau', N'247903', 18.85, N'20080612'); GO This code asks the database engine to create a table named Employees in the Exercise database. After creating the table, it must first one, followed by two records. Then it must process a transaction that consists of creating three records. After that transaction, data entry continues with the addition of a record. For illustration purposes, we included an error in the code for the transaction. The above code would produce:
The resulting table is:
Notice that the code where the transaction was held did not complete and its records were not created.
|
|
|||||||||||||||||||||
|