A trigger is used to perform certain action on the table like insertion, deletion or updation of data. It is database object which is bound to a table and is executed automatically. You can implicitly invoke trigger.
Types of Triggers
There are three action query types that you use in SQL which are:
In this article you will learn trigger, types of trigger and how to create and used trigger in SQL. The only focus on insert trigger in this article.
Create the table name Student and name the column of table is ID, Name and Percentage. After this inset data on student table.
CREATE TABLE Student
ID INT Identity,
Percentage Decimal (10,2)
INSERT INTO Student VALUES ('Tom',90.2);
INSERT INTO Student VALUES (Rowd,85.6);
INSERT INTO Student VALUES ('John',80);
INSERT INTO Student VALUES (Henry,75);
INSERT INTO Student VALUES ('Maria',60.9);
This trigger is fired after an INSERT on the table. Let’s create the trigger as:
CREATE TRIGGER trgAfterInsert ON [dbo].[Studetn]
declare @id int;
declare @name varchar(100);
declare @per decimal(10,2);
declare @audit_action varchar(100);
select @empid=i.ID from inserted i;
select @empname=i.Name from inserted i;
select @empsal=i.Percentage from inserted i;
set @audit_action='Inserted Record -- After Insert Trigger.';
insert into Employee_Test_Audit
PRINT 'AFTER INSERT trigger fired.'
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.
Best WordPress Themes and Plugins with Great Team and Support!