PL/SQL - Triggers



PL/SQL. Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in fact, written to be executed in response to any of the following events −
·        database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
·        database definition (DDL) statement (CREATE, ALTER, or DROP).
·        database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is associated.
                       A trigger is a special kind of a stored procedure that executes in response to certain action on the table like insertion, deletion or updation of data. It is a database object which is bound to a table and is executed automatically. You can’t explicitly invoke triggers. The only way to do this is by performing the required action on the table that they are assigned to.

Creating Triggers

The syntax for creating a trigger is −
CREATE [OR REPLACE ] TRIGGER trigger_name  
{BEFORE | AFTER | INSTEAD OF }  
{INSERT [OR] | UPDATE [OR] | DELETE}  
[OF col_name]  
ON table_name  
[REFERENCING OLD AS o NEW AS n]  
[FOR EACH ROW]  
WHEN (condition)   
DECLARE 
   Declaration-statements 
BEGIN  
   Executable-statements 
EXCEPTION 
   Exception-handling-statements 
END; 
Where,
·        CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with the trigger_name.
·        {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The INSTEAD OF clause is used for creating trigger on a view.
·        {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
·        [OF col_name] − This specifies the column name that will be updated.
·        [ON table_name] − This specifies the name of the table associated with the trigger.
·        [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for various DML statements, such as INSERT, UPDATE, and DELETE.
·        [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger.
·        WHEN (condition) − This provides a condition for rows for which the trigger would fire. This clause is valid only for row-level triggers.

Example

To start with, we will be using the CUSTOMERS table we had created and used in the previous chapters −
Select * from customers;  
 
+----+----------+-----+-----------+----------+ 
| ID | NAME     | AGE | ADDRESS   | SALARY   | 
+----+----------+-----+-----------+----------+ 
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 | 
|  2 | Khilan   |  25 | Delhi     |  1500.00 | 
|  3 | kaushik  |  23 | Kota      |  2000.00 | 
|  4 | Chaitali |  25 | Mumbai    |  6500.00 | 
|  5 | Hardik   |  27 | Bhopal    |  8500.00 | 
|  6 | Komal    |  22 | MP        |  4500.00 | 
+----+----------+-----+-----------+----------+ 
The following program creates a row-level trigger for the customers table that would fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the salary difference between the old values and new values −
CREATE OR REPLACE TRIGGER display_salary_changes 
BEFORE DELETE OR INSERT OR UPDATE ON customers 
FOR EACH ROW 
WHEN (NEW.ID > 0) 
DECLARE 
   sal_diff number; 
BEGIN 
   sal_diff := :NEW.salary  - :OLD.salary; 
   dbms_output.put_line('Old salary: ' || :OLD.salary); 
   dbms_output.put_line('New salary: ' || :NEW.salary); 
   dbms_output.put_line('Salary difference: ' || sal_diff); 
END; 
/ 
When the above code is executed at the SQL prompt, it produces the following result −
Trigger created.
The following points need to be considered here −
·        OLD and NEW references are not available for table-level triggers, rather you can use them for record-level triggers.
·        If you want to query the table in the same trigger, then you should use the AFTER keyword, because triggers can query the table or change it again only after the initial changes are applied and the table is back in a consistent state.
·        The above trigger has been written in such a way that it will fire before any DELETE or INSERT or UPDATE operation on the table, but you can write your trigger on a single or multiple operations, for example BEFORE DELETE, which will fire whenever a record will be deleted using the DELETE operation on the table.

Triggering a Trigger

Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement, which will create a new record in the table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) 
VALUES (7, 'Kriti', 22, 'HP', 7500.00 ); 
When a record is created in the CUSTOMERS table, the above create trigger, display_salary_changes will be fired and it will display the following result −
Old salary: 
New salary: 7500 
Salary difference:
Because this is a new record, old salary is not available and the above result comes as null. Let us now perform one more DML operation on the CUSTOMERS table. The UPDATE statement will update an existing record in the table −
UPDATE customers 
SET salary = salary + 500 
WHERE id = 2; 
When a record is updated in the CUSTOMERS table, the above create trigger, display_salary_changes will be fired and it will display the following result −
Old salary: 1500 
New salary: 2000 
Salary difference: 500 

Benefits of Triggers

Triggers can be written for the following purposes −
  • Generating some derived column values automatically
  • Enforcing referential integrity
  • Event logging and storing information on table access
  • Auditing
  • Synchronous replication of tables
  • Imposing security authorizations
  • Preventing invalid transactions

Types Of Triggers

There are three action query types that you use in SQL which are INSERTUPDATE and DELETE. So, there are three types of triggers and hybrids that come from mixing and matching the events and timings that fire them. Basically, triggers are classified into two main types:
i.            After Triggers (For Triggers)
ii.            Instead Of Triggers

After Triggers

These triggers run after an insert, update or delete on a table. They are not supported for views.
AFTER TRIGGERS can be classified further into three types as:
a.       AFTER INSERT Trigger
b.       AFTER UPDATE Trigger
c.        AFTER DELETE Trigger
Let’s create After triggers. First of all, let’s create a table and insert some sample data. Then, on this table, we will be attaching several triggers.
CREATE TABLE Employee_Test
(
Emp_ID INT,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)
 
INSERT INTO Employee_Test VALUES ('Anees',1000);
INSERT INTO Employee_Test VALUES ('Rick',1200);
INSERT INTO Employee_Test VALUES ('John',1100);
INSERT INTO Employee_Test VALUES ('Stephen',1300);
INSERT INTO Employee_Test VALUES ('Maria',1400);
We creating an AFTER INSERT TRIGGER which will insert the rows inserted into the table into another audit table. The main purpose of this audit table is to record the changes in the main table. This can be thought of as a generic audit trigger.



Now, create the audit table as:
CREATE TABLE Employee_Test_Audit
(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)

(a) After Insert Trigger

This trigger is fired after an INSERT on the table. Let’s create the trigger as:
CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test] 
FOR INSERT
AS
         declare @empid int;
         declare @empname varchar(100);
         declare @empsal decimal(10,2);
         declare @audit_action varchar(100);
 
         select @empid=i.Emp_ID from inserted i;     
         select @empname=i.Emp_Name from inserted i; 
         select @empsal=i.Emp_Sal from inserted i;   
         set @audit_action='Inserted Record -- After Insert Trigger.';
 
         insert into Employee_Test_Audit
           (Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
         values(@empid,@empname,@empsal,@audit_action,getdate());
 
         PRINT 'AFTER INSERT trigger fired.'
GO
The CREATE TRIGGER statement is used to create the trigger. The ON clause specifies the table name on which the trigger is to be attached. The FOR INSERT specifies that this is an AFTER INSERT trigger. In place of FOR INSERTAFTER INSERT can be used. Both of them mean the same.
In the trigger body, table named inserted has been used. This table is a logical table and contains the row that has been inserted. I have selected the fields from the logical inserted table from the row that has been inserted into different variables, and finally inserted those values into the Audit table.
To see the newly created trigger in action, let's insert a row into the main table as:
insert into Employee_Test values('Chris',1500);
Now, a record has been inserted into the Employee_Test table. The AFTER INSERT trigger attached to this table has inserted the record into the Employee_Test_Audit as:

6   Chris  1500.00   Inserted Record -- After Insert Trigger.         2008-04-26 12:00:55.700

(b) AFTER UPDATE Trigger

This trigger is fired after an update on the table. Let’s create the trigger as:
CREATE TRIGGER trgAfterUpdate ON [dbo].[Employee_Test] 
FOR UPDATE
AS
         declare @empid int;
         declare @empname varchar(100);
         declare @empsal decimal(10,2);
         declare @audit_action varchar(100);
 
         select @empid=i.Emp_ID from inserted i;     
         select @empname=i.Emp_Name from inserted i; 
         select @empsal=i.Emp_Sal from inserted i;   
         
         if update(Emp_Name)
                 set @audit_action='Updated Record -- After Update Trigger.';
         if update(Emp_Sal)
                 set @audit_action='Updated Record -- After Update Trigger.';
 
         insert into Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
         values(@empid,@empname,@empsal,@audit_action,getdate());
 
         PRINT 'AFTER UPDATE Trigger fired.'
GO
The AFTER UPDATE Trigger is created in which the updated record is inserted into the audit table. There is no logical table updated like the logical table inserted. We can obtain the updated value of a field from the update(column_name) function. In our trigger, we have used, if update(Emp_Name) to check if the column Emp_Name has been updated. We have similarly checked the column Emp_Sal for an update.
Let’s update a record column and see what happens.
update Employee_Test set Emp_Sal=1550 where Emp_ID=6
This inserts the row into the audit table as:
6  Chris  1550.00  Updated Record -- After Update Trigger.     2008-04-26 12:38:11.843

 

 

 

(c) AFTER DELETE Trigger

This trigger is fired after a delete on the table. Let’s create the trigger as:
CREATE TRIGGER trgAfterDelete ON [dbo].[Employee_Test] 
AFTER DELETE
AS
         declare @empid int;
         declare @empname varchar(100);
         declare @empsal decimal(10,2);
         declare @audit_action varchar(100);
 
         select @empid=d.Emp_ID from deleted d;      
         select @empname=d.Emp_Name from deleted d;  
         select @empsal=d.Emp_Sal from deleted d;    
         set @audit_action='Deleted -- After Delete Trigger.';
 
         insert into Employee_Test_Audit
(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
         values(@empid,@empname,@empsal,@audit_action,getdate());
 
         PRINT 'AFTER DELETE TRIGGER fired.'
GO
In this trigger, the deleted record’s data is picked from the logical deleted table and inserted into the audittable. Let’s fire a delete on the main table. A record has been inserted into the audit table as:
6  Chris   1550.00  Deleted -- After Delete Trigger.  2008-04-26 12:52:13.867
All the triggers can be enabled/disabled on the table using the statement:
ALTER TABLE Employee_Test {ENABLE|DISBALE} TRIGGER ALL
Specific Triggers can be enabled or disabled as:
ALTER TABLE Employee_Test DISABLE TRIGGER trgAfterDelete
This disables the After Delete Trigger named trgAfterDelete on the specified table.

(ii) Instead Of Triggers

These can be used as an interceptor for anything that anyone tried to do on our table or view. If you define an Instead Of trigger on a table for the Delete operation, they try to delete rows, and they will not actually get deleted (unless you issue another delete instruction from within the trigger).
INSTEAD OF TRIGGERS can be classified further into three types as:
a.       INSTEAD OF INSERT Trigger
b.       INSTEAD OF UPDATE Trigger
c.        INSTEAD OF DELETE Trigger



Let’s create an Instead Of Delete Trigger as:
CREATE TRIGGER trgInsteadOfDelete ON [dbo].[Employee_Test] 
INSTEAD OF DELETE
AS
         declare @emp_id int;
         declare @emp_name varchar(100);
         declare @emp_sal int;
         
         select @emp_id=d.Emp_ID from deleted d;
         select @emp_name=d.Emp_Name from deleted d;
         select @emp_sal=d.Emp_Sal from deleted d;
 
         BEGIN
                 if(@emp_sal>1200)
                 begin
                          RAISERROR('Cannot delete where salary > 1200',16,1);
                          ROLLBACK;
                 end
                 else
                 begin
                          delete from Employee_Test where Emp_ID=@emp_id;
                          COMMIT;
                          insert into Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,
                                                        Audit_Timestamp)
                          values(@emp_id,@emp_name,@emp_sal,
                               'Deleted -- Instead Of Delete Trigger.',getdate());
                          PRINT 'Record Deleted -- Instead Of Delete Trigger.'
                 end
         END
GO
This trigger will prevent the deletion of records from the table where Emp_Sal > 1200. If such a record is deleted, the Instead Of Trigger will rollback the transaction, otherwise the transaction will be committed. Now, let’s try to delete a record with the Emp_Sal >1200 as:
delete from Employee_Test where Emp_ID=4
This will print an error message as defined in the RAISE ERROR statement as:
Server: Msg 50000, Level 16, State 1, Procedure trgInsteadOfDelete, Line 15
Cannot delete where salary > 1200
And this record will not be deleted.
In a similar way, you can code Instead Of Insert and Instead Of Update triggers on your tables.


Comments

Popular posts from this blog

what is shell in linux