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

CREATE TABLE  DEPT(
DEPTNO int,
DNAME char(20),
LOC char(20))

2 Create another table for tracking:-

create table track
(Deptno int,
dname char(20),
loc char(20))

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

create trigger insertafter_test on dept
AFTER INSERT
as
begin
insert into track(Deptno,dname,loc)
select inserted.deptno,inserted.dname,inserted.loc from inserted;
end

This is how a insert trigger works.