Advanced Database Lab part SQL Server Trigger
Advanced Database Lab part SQL Server Trigger
A SQL Server trigger is a piece of procedural code, like a stored procedure which is
only executed when a given event happens. There are different types of events that can
fire a trigger. Just to name you a few, the insertion of rows in a table, a change in a
table structure and even a user logging into a SQL Server instance.
There are three main characteristics that make triggers different than stored
procedures:
• In simple words, we can say that, if you want to execute some pre-processing or
post-processing logic before or after the Insert, Update, or Delete in a table then
you need to use Triggers.
Con’t…
Action: A procedure that is executed when the trigger is activated and its
condition is true.
Con’t…
Why do we need DML Triggers in SQL Server?
• DML Triggers are used to enforce business rules and data integrity. These triggers
are very much similar to constraints in the way they enforce integrity.
• So, with the help of DML Triggers, we can enforce data integrity which cannot be
done with the help of constraints that is comparing values with values of another
table, etc.
How to create triggers?
We can create triggers by using the CREATE TRIGGER statement. The statement
specifies the table on which a trigger is defined, the events for which the trigger
Syntax
on [Table_Name]
[ trigger_body ]
Con’t…
Now let me break down this syntax and explain each and every part in detail.
Create Trigger
These two keywords are used to specify that a trigger block is going to be declared.
Trigger_Name
It specifies the name of the trigger. Trigger name has to be unique and shouldn’t repeat.
( Before | After )
This specifies when the trigger will be executed. It tells us the time at which the trigger is initiated, i.e, either
before the ongoing event or after.
Before Triggers are used to update or validate record values before they’re saved to the database.
Con’t…
After Triggers are used to access field values that are set by the system and to effect changes in other records.
The records that activate the after trigger are read-only. We cannot use After trigger if we want to update a
record because it will lead to read-only error.
on [ Table_Name ]
We need to mention the table name on which the trigger is being applied. Don’t forget to use on keyword and
also make sure the selected table is present in the database.
• Row-level trigger gets executed before or after any column value of a row changes
• Column Level Trigger gets executed before or after the specified column changes
• [ trigger_body]
Con’t…
Where the Triggers are Created in SQL Server?
• In SQL Server, the Triggers are created within the Trigger folder which you can find when you expand the table as
shown in the below image.
Categories of Triggers
Triggers can be divided into three main categories
1. DDL Triggers
2. DML Triggers
3. Logon triggers
1. DDL Triggers
ª In SQL Server we can create triggers on DDL statements (like CREATE, ALTER and DROP)
and certain system-defined Stored Procedures that does DDL-like operations.
ª This type of trigger is fired against DDL statements like Drop Table, Create Table or Alter
Table. DDL Triggers are always After Triggers.
ª These triggers are created at the database level or server level based on the type of DDL event.
In SQL Server we can create triggers on DML statements (like INSERT, UPDATE and DELETE)
The After trigger (using the FOR/AFTER CLAUSE) fires after SQL Server finishes the execution of
the action successfully that fired it. That is once the DML statement (such as Insert, Update, and
Example: If you insert a record/row into a table then the trigger related/associated with the insert
event on this table will fire only after the row passes all the constraints, such as primary key
constraint and some rules. If the record/row insertion fails, SQL Server will not fire the After
b.Instead of Trigger (using INSTEAD OF CLAUSE)
• The Instead of Trigger (using the INSTEAD OF CLAUSE) fires before SQL Server starts the execution of
the action that fired it. This is different from the AFTER trigger that fires after the action that caused it to fire.
We can have an INSTEAD OF insert/update/delete trigger on a table that successfully executed but does not
include the actual insert/update/delete to the table. INSTEAD OF triggers executes instead of the firing
statement. In other words, this type of trigger replaces the firing statement. This is very useful in cases where
you need to have cross database referential integrity. Specifies that the DML trigger launches instead of the
triggering SQL statement, thus, overriding the actions of the triggering statements. You can't specify
• Example: If you insert a record/row into a table then the trigger related/associated with the insert event on
this table will fire before the row passes all the constraints, such as primary key constraint and some rules. If
the record/row insertion fails, SQL Server will fire the Instead of Trigger.
con’t…
As we have already understood how to create a trigger, now let’s understand the two variants of the
trigger those are Before insert and After insert. in order to implement them, let’s create a student
Example:
);
con’t…
before INSERT
ON student
Here when we insert data into the student table automatically the trigger will be
invoked. The trigger will add 100 to the marks column into the student column.
con’t…
To use this variant we need one more table i.e, Percentage where the trigger will store the results. Use the
per int );
con’t…
after insert
ON student
Here when we insert data to the table, total_mark trigger will store the result in the Final_mark table.
3.Logon Triggers
Logon triggers are a special type of triggers that fire when a LOGON event of SQL
Server is raised. This event is raised when a user session is being established with SQL
Server that is made after the authentication phase finishes, but before the user session is
actually established. Hence, all messages that we define in the trigger, such as error
messages, will be redirected to the SQL Server error log. Logon triggers do not fire if
authentication fails. We can use these triggers to audit and control server sessions, such
as to track login activity or limit the number of sessions for a specific login.
This type of trigger is fired against a LOGON event before a user session is established
to the SQL Server.
con’t…
triggers fire after successful authentication and before establishing the user
session.
• LOGON triggers are created at the server level and are useful below cases.
You can create a DML Trigger in SQL Server by using the following syntax
Enabling and disabling DML triggers on a table
• Navigate to triggers folder at the table level, select the trigger, Right click on trigger and Click
on Enable/Disable to Enable or disable the trigger using SSMS.
• Disabling specific SQL Server trigger on a table using T-SQL.
• Disable trigger trigger_name on table name
• DISABLE TRIGGER TR_UPD_Locations2 on Locations
Operations in Triggers
Display A Trigger
The below code will display all the triggers that are present.
The below code will display all the triggers that are present in a particular database.
SHOW TRIGGERS
IN database_name;
In the above example, all the triggers that are present in the database named CCI will be displayed.
Examples
GO
-- Insert data into Employee table
• Create a Trigger that will restrict the INSERT operation on the Employee table.
CREATE TRIGGER trInsertEmployee
ON Employee
FOR INSERT
AS BEGIN
PRINT 'YOU CANNOT PERFORM INSERT OPERATION' ROLLBACK TRANSACTION
END
Let’s try to insert the following record into the employee table.
INSERT INTO Employee VALUES (6, ‘Saroj’, 7600, ‘Male’, 1)
When you try to execute the above Insert statement it gives you an error
Example2: For Update DML Trigger
Create a Trigger which will restrict the UPDATE operation on the Employee table.
CREATE TRIGGER trUpdateEmployee
ON Employee
FOR UPDATE
AS
BEGIn
PRINT 'YOU CANNOT PERFORM UPDATE OPERATION'
ROLLBACK TRANSACTION
END
Let’s try to update one record in the Employee table
UPDATE Employee SET Salary = 90000 WHERE Id = 1
When you try to execute the above Update statement it will give you the following error
Example3: For Delete DML Triggers
Create a Trigger which will restrict the DELETE operation on the Employee table
CREATE TRIGGER trDeleteEmployee
ON Employee
FOR DELETE
AS
BEGIN
PRINT 'YOU CANNOT PERFORM DELETE OPERATION'
ROLLBACK TRANSACTION
END
Let’s try to delete one record from the Employee table
DELETE FROM Employee WHERE Id = 1
When we try to execute the above Delete statement, it gives us the below error
Example4: For Insert/Update/Delete DML Trigger
Create a trigger that will restrict all the DML operations on the Employee table.
Now let’s create a trigger that will restrict all the DML Operations on the Employee table.
ON Employee
AS
BEGIN
ROLLBACK TRANSACTION
END
Now, you cannot perform any DML operations on the Employee table because those operations are restricted by a trigger called
Example 5: Drop triggers
Example:
Create a Trigger which will restrict all the DML operations on the Employee
table before 1 pm.
ALTER TRIGGER trAllDMLOperationsOnEmployee
ON Employee
FOR INSERT, UPDATE, DELETE
AS
BEGIN
IF DATEPART(HH,GETDATE()) < 13
BEGIN
PRINT 'INVALID TIME'
ROLLBACK TRANSACTION
END
Questions
1. Create a trigger that prevents modification of salary values in the employee table?
Given information about Employee table.
create database TriggersSQL
create table Employee(
Id int primary key ,
fname varchar(20),
sex char,
salary int
go
create trigger SalaryTrigger
on Employee
for update
as
if (update(salary))
begin
Raiserror ('Slary information should not be modified',16,1)
rollback transaction
end
go
2 The following code is also used to prevent deletion of more than 5 books at a time
from books table.
go
create trigger Trdelete_book
on Books
for delete
as
if (select count(*) from deleted ) >5
begin
Raiserror('Hey buddy u cant delete book more than 5',16,1)
rollback transaction
end
go