Categories
Sql Server

INSERT Trigger in Sql Server

INSERT Trigger Works Sql Server

INSERT TRIGGER is a trigger that execute itself whenever an INSERT statement inserts data into any table or view on which the trigger was configured.

When an INSERT trigger fires itself, new rows are also added on both the trigger table and inserted table. The inserted table is a logical table that holds a copy of the rows that have been inserted by user. The inserted table contains the logged insert activity from the INSERT statement. The inserted table allows you to reference logged data from the initiating INSERT statement. The rows in a inserted table are always duplicates of one or more rows in the trigger table.

How to Create a insert trigger:-

1 Create a table:-

1CREATE TABLE  DEPT(
2DEPTNO int,
3DNAME char(20),
4LOC char(20))

2 Create another table for tracking:-

1create table track
2(Deptno int,
3dname char(20),
4loc char(20))

3 Now create the trigger which works when any insert is happened on dept table and logged into track table automatically.

1create trigger insertafter_test on dept
2AFTER INSERT
3as
4begin
5insert into track(Deptno,dname,loc)
6select inserted.deptno,inserted.dname,inserted.loc from inserted;
7end

This is how a insert trigger works.