Professional Documents
Culture Documents
• Triggers
• QBE
Triggers
• In SQL server there are 3 types of triggers
– DML triggers
– DDL triggers
– Logon trigger
• DML triggers are fired automatically in response to DML events
(INSERT, UPDATE & DELETE)
• DML triggers can again classified into 2 types
– After triggers (sometimes called as FORtriggers)
– Instead of triggers
Triggers
• After triggers, fires after the triggering action.
– The INSERT, UPDATE, and DELETE statements, causes an after trigger
to fire after the respective statements complete execution.
• INSTEAD of triggers, fires instead of the triggering action.
– The INSERT, UPDATE, and DELETE statements, causes an INSTEAD OF
trigger to fire INSTEAD OF the respective statement execution (i.e.,
before executing respective statement).
After/For Trigger
Create trigger tr_employee_ForInsert
ON HR.employees
FOR INSERT
AS
BEGIN
insert into HR.employeeAudit values ('New employee with Id = ‘ + cast(@Id as nvarchar(5)) + ' is
added at ‘ + cast(GetDate() as nvarchar(20))
End
ON HR.employees
FOR DELETE
AS
BEGIN
insert into HR.employeeAudit values ('An existing employee with Id = ' + cast(@Id as nvarchar(5))
End
ON HR.employees
FOR update
AS
BEGIN
End
• Note:
• The After trigger for UPDATE event, makes use of both inserted and delete tables.
• The inserted table contains the updated data and the deleted table contains the old data.
Instead of InsertTrigger
create trigger tr_vWEmployeeDetails_InsteadofInsert
on vWEmployeeDetails
Instead of Insert
as
Begin
on i.department_name = d.department_name
if(@DeptId is null)
Begin
return
End
• Note:
• The After trigger for UPDATE event, makes use of both inserted and delete tables.
• The inserted table contains the updated data and the deleted table contains the old data.
Instead of update Trigger
create view vWEmployeeDetails2
as
from HR.Employees e
join HR.departments d
on e.department_id = d.department_id
• Update the view, in such a way that, it affects, both the underlying tables
employee_id =211
Instead of update Trigger
End
if(update(department_name))
Begin
on i.department_name = d.department_name
if(@DeptId is NULL)
Begin
return
END
if(update(first_name))
Begin
End
Instead of Delete Trigger
create trigger tr_vWEmployeeDetails_InsteadofDelete
on vWEmployeeDetails2
instead of delete
as
Begin
Delete HR.employees
on HR.employees.employee_id = deleted.employee_id
END
Users only have to enter the criteria for their search and the DBMS software will run the query. This differs from SQL where
a specific code is required for running queries of a databases.
• Triggers
• QBE