What is Transaction.
A transaction is a set of operations performed so all operations are guaranteed to succeed or fail as one unit.
When to Use Transactions
You should use transactions when several operations must succeed or fail as a unit.
The following are some frequent scenarios where use of transactions is recommended:
In batch processing, where multiple rows must be inserted, updated, or deleted as a single unit
Whenever a change to one table requires that other tables be kept consistent
When modifying data in two or more databases concurrently
In distributed transactions, where data is manipulated in databases on various servers.
Understanding ACID Properties.
1. Atomicity:
2. Consistency
3. Isolation
4. Durability
Example:
A transaction is a set of operations performed so all operations are guaranteed to succeed or fail as one unit.
When to Use Transactions
You should use transactions when several operations must succeed or fail as a unit.
The following are some frequent scenarios where use of transactions is recommended:
In batch processing, where multiple rows must be inserted, updated, or deleted as a single unit
Whenever a change to one table requires that other tables be kept consistent
When modifying data in two or more databases concurrently
In distributed transactions, where data is manipulated in databases on various servers.
Understanding ACID Properties.
1. Atomicity:
2. Consistency
3. Isolation
4. Durability
Example:
- create procedure sp_Trans_Test
- @newpersonid nvarchar(5),
- @newfirstname nvarchar(10)
- @newcompanyname nvarchar(15),
- @oldpersonid nvarchar(5)
- as
- declare @inserr int
- declare @delerr int
- declare @maxerr int
- set @maxerr = 0
- BEGIN TRANSACTION
- -- Add a person
- insert into person (personid, firstname, company)
- values(@newpersonid, @newfirstname, @newcompanyname)
- -- Save error number returned from Insert statement
- set @inserr = @@error
- if @inserr > @maxerr
- set @maxerr = @inserr
- -- Delete a person
- delete from person
- where personid = @oldpersonid
- -- Save error number returned from Delete statement
- set @delerr = @@error
- if @delerr > @maxerr
- set @maxerr = @delerr
- -- If an error occurred, roll back
- if @maxerr <> 0
- begin
- ROLLBACK
- print 'Transaction rolled back'
- end
- else
- begin
- COMMIT
- print 'Transaction committed'
- end
- print 'INSERT error number:'+ cast(@inserras nvarchar(8))
- print 'DELETE error number:'+ cast(@delerras nvarchar(8))
- return @maxerr