0
20kviews
Explain Assertions and Triggers in detail.

Mumbai University > Computer Engineering > sem 4> database management system

Marks: 10M

Year: May16

1 Answer
0
82views

ASSERTION :

The CREATE ASSERTION statement names a new Constraint and defines the Constraint's deferral mode, initial constraint check time and its CHECK search condition. The required syntax for the CREATE ASSERTION statement is:

CREATE ASSERTION <Constraint name> 
CHECK (search condition) 
[ <constraint attributes> ]

CREATE ASSERTION defines a new rule that will constrain the set of valid values for one or more Base tables. An Assertion is owned by the Schema it belongs to.

⦁ The <constraint name=""> identifies the Assertion and the Schema that it belongs to. A <constraint name=""> that includes an explicit <schema name=""> qualifier belongs to the Schema named. A <constraint name=""> that does not include an explicit <schema name=""> qualifier belongs to the SQL-session default Schema. (In both cases, that Schema must, of course, own the Tables for which the Assertion is defined.) The <constraint name=""> must be unique (for all Constraints and Assertions) within the Schema that owns it.

If CREATE ASSERTION is part of a CREATE SCHEMA statement, the <constraint name="">, if explicitly qualified, must include the <schema name=""> of the Schema being created; that is, it isn't possible to create an Assertion belonging to a different Schema from within CREATE SCHEMA. For example, this SQL statement will not return an error because the <constraint name=""> will default to include the qualifying <schema name="">:

REATE SCHEMA bob 
  CREATE TABLE Table_1 (column_1 SMALLINT) 
  CREATE ASSERTION constraint_1 
    CHECK ((SELECT AVG(column_1) FROM Table_1 >40) NOT DEFERRABLE;
-- creates an Assertion called BOB.CONSTRAINT_1 in Schema BOB

This SQL statement will not return an error either because the <constraint name=""> explicitly includes a qualifying <schema name=""> that matches the name of the Schema being created:

CREATE SCHEMA bob 
  CREATE TABLE bob.Table_1 (column_1 SMALLINT)
  CREATE ASSERTION bob.constraint_1 
      CHECK ((SELECT AVG(column_1) FROM Table_1 >40) NOT DEFERRABLE;
-- creates an Assertion called BOB.CONSTRAINT_1 in Schema BOB

Example:

REATE TABLE Table_1 ( 
  column_1 SMALLINT, 
  column_2 VARCHAR(4)); 

CREATE ASSERTION constraint_1 
  CHECK ((SELECT AVG(column_1) FROM Table_1 >40) NOT DEFERRABLE;

CONSTRAINT_1 is violated if the average of the TABLE_1.COLUMN_1 values is less than 41. Assume that TABLE_1 contains one row, where COLUMN_1 contains 42. This SQL statement would then violate CONSTRAINT_1:

INSERT INTO Table_1 (column_1) VALUES (38);
because a search condition that evaluates to FALSE violates the Constraint. Both of these SQL statements, however, would satisfy CONSTRAINT_1:

INSERT INTO Table_1 (column_1) VALUES (100); 
-- a search condition that evaluates to TRUE satisfies the Constraint

INSERT INTO Table_1 (column_1) VALUES (NULL); 
-- NULL is allowed; a search condition that evaluates to UNKNOWN satisfies the Constraint

Trigger:

A trigger is a special kind of a store 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 no the table that they are assigned to.

Types Of Triggers

There are three action query types that you use in SQL which are INSERT, UPDATE 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:

1.After Triggers (For Triggers)

2 Instead Of Triggers

1. 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:

  1. AFTER INSERT Trigger.

  2. AFTER UPDATE Trigger.

  3. 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, I will be attaching several triggers.

CREATE TABLE Employee_Test
(
Emp_ID INT Identity,
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);

I will be 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 INSERT,

AFTER 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, lets 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 audit table. 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.

2. 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:

  1. INSTEAD OF INSERT Trigger.

  2. INSTEAD OF UPDATE Trigger.

  3. 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.

Please log in to add an answer.