What we call a transaction in SQL is logical set or sequence of operations which belong to this transaction. SQL Transactions can be used if we perform some changes in a databases.
Advantage of transactions managing is that performed changes are reversible and we always need to use command COMMIT for confirmation or use ROLLBACK command to reverse the transaction/changes.
What is The Advantage of Managing Transactions?
Imagine a situation when you perform multiple UPDATE and INSERT operations. There can always occur an error during these operations or you can simply have a typo in the script. In case you did not use transaction (for example in combination with TRY/CATCH) you will have to seek which parts of script have been performed and which have not. You can even get to a such trouble that you will need db backup.
All operations performing some change in the database can be part of a transaction:
- DML operation (data manipulation language) – INSERT, UPDATE, DELETE
- DDL operation (data definition language) – for example. CREATE TABLE, CREATE INDEX etc.
If we define sql transaction and perform some DML operation in it, object above which we perform DML will get locked – row lock, page lock, table lock
Transaction is framed in sql relation. Transaction (and locks) are still active if the relation is open.
--DDL or DML opertion
Transactions can be nested so you can create transaction inside of transaction (nested transaction).
Functions @@TRANCOUNT and XACT_STATE()
These functions serve to detect existence, state and count of nested transactions.
A) @@TRANCOUNT – using this system function will tell us number of transactions in session
- 0 means no active transaction
- >0 means active transaction
- >1 exists active nested transaction
B) XACT STATE() – this function is similar to previous one but gives us different information
- 0 no active transaction
- 1 existence of unconfirmed transaction which can be confirmed (number of nested transactions is unimportant)
- -1 existence of unconfirmed transaction which cannot be confirmed due to an error
XACT STATE() Synatx:
Savepoints in a transaction
Savepoints are useful feature. They enable user to define places within the transaction to where you can return using ROLLBACK. Therefore, you do not have to call out the whole transaction. You will only return a few steps back.
Syntax of sql SAVEPOINT creation
--DDL or DML operation 1
SAVE TRANSACTION <name 1>
--DDL or DML operation 2
SAVE TRANSACTION <name 2>
ROLLBACK <name 1>;