Chapter 12 Implementing Transactions, Error Handling, and Dynamic SQL Flashcards
What is a transaction?
A transaction is a logical unit of work. Work completes as a whole unit or none of it does. For SQL Server, all changes to data take place in the context of a transaction. In other words, all operations that in any way write to the database are treated by SQL Server as transactions. This includes DML (INSERT, UPDATE) and DDL (CREATE TABLE, CREATE INDEX). Even single SELECT statements are a type of transaction (read-only transactions).
What do the terms commit and rollback mean?
The terms commit and rollback refer to the act of controlling the result of transactions in SQL Server. When the work of a transaction has been approved by the user, SQL Server completes the transaction’s changes by committing them. If an unrecoverable error occurs or the user decides not to commit, then the transaction is rolled back.
What does the ACID acronym stand for?
- (A) Atomicity - Every transaction is an atomic unit of work. All database changes in a transaction succeed or none of them succeed,
- (C) Consistency - Every transaction whether successful or not leaves the database in a consistent state as defined by all objects and database constraints,
- (I) Isolation - In regards to database changes, every transaction looks as though it occurs in isolation from other transactions. The degree of isolation can vary based on isolation level.
- (D) Durability - Every transaction endures through an interruption of service. When service is restored, all committed transactions are committed and all uncommitted transactions are rolled back.
How does SQL Server enforce transactional isolation?
SQL Server ensures that when a transaction makes multiple changes to the database, none of the objects being changed by that transaction are allowed to be changed by any other transaction.
In other word’s, one transaction’s changes are isolated from any other transaction’s activities. If two transactions want to change the same data, one of them must wait until the other transaction is finished.
SQL Server accomplishes transactional isolation by means of locking, as well as, row versioning. SQL Server locks objects (rows and tables) to prevent other transactions from interfering.
How does SQL Server maintain transactional durability?
SQL Server maintains transactional Durability by using the database transaction log. Every database change (DML or DDL) is first written to the transaction log with the original version of the data (in the case of updates and deletes).
For example, if the database server shuts down unexpectedly just after the fact of a successful commit has been written to the transaction log, when SQL Server starts back up, the transaction will be rolled forward and finished.
On the other hand, if the database server shuts down unexpectedly before a successful commit could be written to the log, when the database server starts back up, the transaction will be rolled back and any database changes undone.
Which database has transaction logs?
Every database and every system database has a transaction log to enforce transaction durability.
Can you turn off the transaction log?
No.
You cannot turn off a database’s transaction log or remove it. Some operations can somewhat reduce transaction logging. But all database changes are always written first to the transaction log.
Why is it important for SQL Server to maintain the ACID properties of transactions?
To ensure that the integrity of the database data will not be compromised.
What are the two types of transactions?
- System transactions
- System transactions are not under user control. They maintain internal persistent system tables.
- User transactions
- User transactions are created by users in the process of changing and/or reading data whether automatically, implicitly, or explicitly.
What DMV can you query to observe the names of the transactions?
sys.dm_tran_active_transactions
The default name for a user transactions is user_transaction if one is not assigned by the user.
SELECT *
FROM sys.dm_tran_active_transactions
WHERE Name = ‘user_transaction’
DMV = Data Management Views
What command(s) do you use to mark the start of a transaction - explicitly?
BEGIN TRANSACTION or BEGIN TRAN.
A name can be assigned to the transaction.
DECLARE @TranName VARCHAR(20);
SELECT @TranName = ‘MyTransaction’;
BEGIN TRANSACTION @TranName;
USE AdventureWorks2012;
DELETE FROM AdventureWorks2012.HumanResources.JobCandidate WHERE JobCandidateID = 13;
COMMIT TRANSACTION @TranName;
GO
What command(s) do you use to mark the end of a transaction by committing it or rolling it back?
COMMIT TRANSACTION, COMMIT TRAN, COMMIT WORK, or COMMIT.
To roll back a transaction use ROLL BACK TRANSACTION, ROLLBACK TRAN, ROLLBACK WORK, or ROLLBACK.
Transactions can be nested.
What does the @@TRANCOUNT system function indicate?
@@TRANCOUNT can be queried to find the level of the transaction.
@@TRANCOUNT = 0 indicates that the code is not within a transaction.
@@TRANCOUNT > 0 indicates that there is an active transaction
@@TRANCOUNT > 1 indicates the level of a nested transaction.
What does the XACT_STATE() function indicate?
XACT_STATE() = 0 Indicates that there is no active transaction.
XACT_STATE() = 1 Indicates that there is an uncommitted transaction and it can be committed but the nesting level is not reported.
XACT_STATE() = -1 Indicates that there is an uncommitted transaction and it cannot be committed due to a prior fatal error.
What are the three modes of user transactions in SQL Server?
- Autocommit
- Implicit transaction
- Explicit transaction
How does the autocommit mode of transactions behave?
Autocommit is the default transaction management mode. In autocommit mode, single DML and DDL statements are executed in the context of a transaction that will automatically be committed when the statement succeeds or automatically rolled back if the statement fails.
In the autocommit mode, you do not issue any surrounding transactional commands such as BEGIN TRAN, ROLLBACK TRAN, or COMMIT TRAN.
Also, @@TRANCOUNT is not normally detectable. Whatever changes you make to the database are automatically handled, statement by statement, as transactions.
How does the implicit mode of transactions behave?
In the implicit transaction mode, when one or more DML or DDL statements or a SELECT statement is issued, SQL Server starts a transaction, increments @@TRANCOUNT, but does not automatically commit or roll back the statement.
You must issue a COMMIT or ROLLBACK to finish the transaction.
Implicit transaction mode is not the default, so you must enter the following command:
SET IMPLICIT_TRANSACTIONS ON; or SET ANSI_DEFAULTS ON;
Note that @@TRANCOUNT is incremented as soon as you enter any command to change data.
Also, implicit transactions can span batches.
How does the explicit mode of transactions behave?
An Explicit Transaction occurs when the Begin Transaction command is issued and committed when the COMMIT TRANSACTION command is issued. When the Begin Transaction command is issued the @@TRANCOUNT is incremented by 1.
Note that when the Explicit Transaction mode is used within the Implicit Transaction mode, the value of @@TRANCOUNT will jump to 2 immediately after the BEGIN TRAN command - effectively becoming a nested transaction.
SET IMPLICIT_TRANSACTIONS ON; or SET ANSI_DEFAULTS ON;
AND
Begin Transaction
@@TRANCOUNT = 2
….
Commit Transaction
What are some advantages of using implicit transactions?
- After a command has been completed, the transaction can still be rolled back
- Because the COMMIT statement must be issued, mistakes can be found after the execution of a command.
What are some disadvantages of using implicit transactions?
- Any locks are held until the transaction receives the COMMIT command. Therefore, the locks can block other users from doing their work.
- It is not the standard method of using SQL Server, you must remember to set it for your session.
- If it is forgotten to commit an implicit transaction, the locks remain open.
- The implicit transaction mode does not work well with explicit transactions because it causes the @@TRANCOUNT value to increment to 2
Can transactions span batches?
Yes.
Both implicit and explicit transactions can span batches - that is, GO statements.
However, it is a best practice to ensure that each transaction takes place in one batch.
What are nested transactions?
When explicit transactions are nested, they are called nested transactions. In this scenario, the behavior of COMMIT and ROLLBACK change when you nest transactions.
An inner COMMIT statement has no real effect on the transaction - only decrementing @@TRANCOUNT by 1.
Only the outermost COMMIT statement will commits the transaction.
Also, note that it doesn’t matter at what level a ROLLBACK command is issued. A transaction can only contain one ROLLBACK command and it will roll back the entire transaction and reset the @@TRANCOUNT to 0.
How do you mark a transaction?
An explicit transaction can be named by putting the identifier after the BEGIN TRAN statement. Transaction names must follow the rules for SQL identifiers; however, only the first 32 characters are acknowledged. The transaction name is displayed in the name column of the sys.dm_tran_active_transactions DMV.
BEGIN TRANSACTION Tran1;
Note that SQL Server only records transaction names for the outermost transaction. If you have nested transactions, any names for the nested transactions are ignored.
Named transactions are used for placing a mark in the transaction log in order to specify a point at which one or more databases can be restored. When the transaction is recorded in the transaction log, the transaction mark is also recorded.
BEGIN TRAN Tran1 WITH MARK; COMMIT TRAN;
How do you restore the database to a specific transaction mark?
RESTORE DATABASE TSQL2012 FROM DISK
=
‘C:\SQLBackups\TSQL2012.bak’
WITH NORECOVERY;
GO
RESTORE LOG TSQL2012 FROM DISK
=
‘C:\SQLBackups\TSQL2012.trn’
WITH STOPMARK
=
‘Tran1’;
GO
The transaction name, WITH STOPMARK = ‘Tran1’, must be used
A description after the clause WITH MARK, but SQL ignores it.
To restore just before the transaction, use WITH STOPBEFOREMARK
You can recover the dataset by restoring with either WITH STOPMARK or WITH STOPBEFOREMARK.
RECOVERY can be added to the WITH list but it has no effect.
What are Savepoints?
Savepoints are locations within a transaction that can be used to roll back a selective subset of work.
A savepoint can be defined by using the SAVE TRANSACTION command.
The ROLLBACK statement must reference the savepoint.
Otherwise, if the statement is unqualified, it will rollback the entire transaction.
What are Cross-database transactions?
Cross-database transactions span two or more databases on a single instance of SQL Server without any additional work on the user’s part.
SQL Server preserves the ACID properties of cross-database transactions without any additional considerations.
There are limitations on database mirroring when using cross-database transactions. A cross database transaction may not be preserved after a failover of one of the databases.
What are Distributed transactions?
Distributed transactions span more than one server by using a linked server connection.
How many COMMITs must be executed in a nested transaction to ensure that the entire transaction is committed?
One COMMIT must be issued for each level of the nested transaction. However, only the last COMMIT actually commits the entire transaction.
What are the two general modes of locking in SQL Server?
- Shared locks -
- Used for sessions that read ‘data - readers’.
- Exclusive locks -
- Used for changes to ‘data - writers’.
Note: There are more advanced modes called update, intent, and schema locks used for special purposes.
What happens when a session sets out to change data?
SQL Server will attempt to secure an exclusive lock on the objects in question. These exclusive locks always occur in the context of a transaction, even if only in the autocommit mode. When a session has an exclusive lock on an object (row, table), no other transaction can change that data until this transaction either commits or rolls back.
Except in special isolation levels, other sessions cannot even read exclusively locked objects.
What happens when a session sets out to read data?
By default, SQL Server will issue very brief shared locks on the resource (row and table). Two or more sessions can read the same objects because shared locks are compatible with other shared locks.
What happens when a session has a resource locked exclusively?
No other session can read the resource.
in addition, no other session can to write to the resource.
Other sessions must wait until the first session releases it’s exclusive lock.
Only shared locks are compatible with each other.
An exclusive lock is not compatible with any other kind of lock.
What is the most granular type of resource?
The most granular type of resource for SQL Server is the row of a table. However, SQL Server can place a lock on an entire page or an entire table.
How long are exclusive locks held?
Exclusive locks are held to the end of the transaction (commit or rollback).
How long are shared locks held?
Shared locks are released as soon as the data is read, and they are not held to the end of the transaction except in higher isolation levels.
What is a deadlock?
A deadlock results from mutual blocking between two or more sessions. This occurs due to a cyclical relationship between two or more commands. SQL Server detects this cycle as a deadlock between the two sessions, aborts one of the transactions, and returns an error message 1205 to the client.
Can readers block writers?
Yes.
Though only momentarily, because any exclusive lock request has to wait until a shared lock is released.
Can a SELECT statement be involved in a deadlock?
Yes.
If the SELECT statement locks some resource that keeps a second transaction from finishing, and the SELECT cannot finish because it is blocked by the same transaction, the deadlock cycle results.
What are the 6 different isolation levels?
- READ COMMITTED
- READ COMMITTED SNAPSHOT
- SNAPSHOT
- READ UNCOMMITTED
- REPEATABLE READ
- SERIALIZABLE