You are on page 1of 12

Triggers and Transaction Management

TCS Internal
1
Objective

To be able to learn the implementation of triggers and SQL


Server transactions

TCS Internal
2
Scope

 Introduction to Triggers
 Creating a trigger
 Transaction Management
 Locks

TCS Internal
3
Introduction to Trigger

 SQL Server provides a mechanism called a trigger for


enforcing procedural integrity constraints.

TCS Internal
4
How trigger work

 A trigger is a mechanism that is invoked when a particular


action occurs on a particular table. Each trigger has three
general parts:

 Name
 Action
 Execution

 The action of the trigger either be an INSERT, an UPDATE,


or a DELETE statement.

 The execution part of the trigger usually contains a stored


procedure or a batch.

TCS Internal
5
Creating a Trigger

 SQL Server 2005 allows us to create trigger using either


Transact SQL or CLR programming languages such as C#
and Visual Basic 2005.

TCS Internal
6
Creating a Trigger (Transact-SQL)

 A trigger is created using the CREATE TRIGGER statement, which has


the follow form:

Syntax:

CREATE TRIGGER [schema_name.]trigger_name


ON table_name | view_name
[WITH dml_trigger_option]
{FOR | AFTER|INSTEAD OF} { [INSERT][,][UPDATE][,][DELETE]}
[WITH APPEND]
AS sql_statement | EXTERNAL NAME method_name

TCS Internal
7
Transaction Management
 A transaction is a logical unit of work.

 Any single SQL statement is considered to be a single unit of


work whether it affects only a single row or multiple rows within
the table.

 In SQL Server a transaction is implicit.

 Explicit transactions can be defined by the user by including the


SQL statements enclosed within BEGIN TRANSACTION and
COMMIT TRANSACTION.

 In creating explicitly defined transactions, the following


statement are used.

 BEGIN TRANSACTION
 COMMIT TRANSACTION
 ROLLBACK TRANSACTION
 SAVE TRANSACTION

TCS Internal
8
Database consistency / Concurrency

 When two or more users access the database concurrently,


SQL Server uses locking to ensure that their actions don’t
interfere each other.

 Locking prevents one user from reading the data which is


being changed by the other users.

 It also prevents users from making more than one change


to a record at any one time.

TCS Internal
9
Isolation Levels
 SQL Server supports file isolation levels:

 READ UNCOMMITED
 READ COMMITED
 REPEATABLE READ
 SNAPSHOT
 SERIALIZABLE

TCS Internal
10
Deadlock

 A deadlock is a special situation in which two transactions


block the progress of each other.

 The first transaction has a lock on some database object


that the other transaction wants to access and vice versa .

TCS Internal
11
Summary

 Introduction to Triggers
 Creating a trigger
 Transaction Management
 Locks

TCS Internal
12

You might also like