Reader Level:
ARTICLE

Triggers in Sql Server

Posted by Deepak Arora Articles | SQL October 17, 2012
In this artcle I describe triggers
  • 0
  • 0
  • 7009

Introduction

We can define a Trigger as "A Trigger is a Database object just like a stored procedure or we can say it is a special kind of Stored Procedure which fires when an event occurs in a database.".

Difference between Stored Procedure and trigger:

Triggers fire implicitly while Stored Procedures fire explicitly.

Type of Triggers:


There are two types of Triggers:

  1. DDL Trigger
  2. DML trigger

DDl Triggers:

They fire in response to DDL (Data Definition Language) command events that start with Create, Alter and Drop. Like Create_table, Create_view, drop_table, Drop_view and Alter_table.

Code of DDL Trigger:

create trigger saftey

on database

for

create_table,alter_table,drop_table

as

print'you can not create ,drop and alter table in this database'

rollback;

 

Output:

When we create, alter or drop any table in a database then the following message appears:


DDl-trigers-in-sql.jpg
DML Triggers:

They fire in response to DML (Data Manipulation Language) command events that start with with Insert, Update and Delete. Like insert_table, Update_view and Delete_table.

Code of DML Trigger:

create trigger deep

on emp

for

insert,update,delete

as

print'you can not insert,update and delete this table i'

rollback;

 

Output:

When we insert, update or delete in a table in a database then the following message appears:

dml-triggers-in-sql.jpg
DML triggers are two type:

AFTER Triggers:

AFTER triggers are executed after the action of an INSERT, UPDATE, or DELETE statement.
 

create trigger insertt

on emp

after insert

as

begin

insert into empstatus values('active')

end 

Output:


aftertrigger-in-sql.jpg

INSTEAD Of Triggers:

It will tell the database engine to execute the trigger instead of executing the statement. For example an insert trigger executes when an event occurs instead of the statement that would insert the values in the table .
 

CREATE TRIGGER instoftr

ON v11

INSTEAD OF INSERT

AS

BEGIN

INSERT INTO emp

SELECT I.id, I.names

FROM INSERTED I

 

INSERT INTO emp1values

SELECT I.id1, I.name1

FROM INSERTED I

END

When we insert data into a view by the following query then it inserts values in both tables :

insert into v11 values(1,'d','dd')

 

You can see both tables by the folowing query:

select * from emp

select * from emp1values

Output:

insteedofcorsor-in-sql.jpg


Summary

In this article I described Triggers in SQL Server. I hope this article has helped you in understanding this topic. Please share it. If you know more about this, your feedback and constructive contributions are welcome.

COMMENT USING

Trending up