Let us see it with an example,
First, we can create two new tables, the first one is 'Employee', that is master table and another one is the trigger reflaction table, that is 'EmployeeTriggerAction'. We will see, when a user enters a new record in Employee Master table, at the same time trigger will be fired and we will insert that table's primary ID and Action name, which is fired.
- 1) Employee
- CREATE TABLE [dbo].[Employee](
- [Id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
- [Name] [nvarchar](50) NULL,
- [Salary] [nvarchar](50) NULL,
- GO
- 2) EmployeeTriggerAction
- CREATE TABLE [dbo].[EmployeeTriggerAction]
- (
- [InsertedId] [int] NULL,
- [ActionFired] [nvarchar](50) NULL
- )
- Go
Now, let us create Insert trigger for Employee Master table.
- CREATE TRIGGER trg_InsertEmployee
- ON [dbo].[Employee]
- AFTER INSERT
- AS
- DECLARE @EmpId int
- BEGIN
- SELECT @EmpId=Id FROM INSERTED
- -- HERE WE CHECK FOR ID NOT NULL
- IF(@EmpId IS NOT NULL)
- BEGIN
- -- IF @EmpId IS NOT NULL THEN WE WILL INSERT THAT ID WITH ACTION NAME IN A NEW TABLE
- PRINT 'AFTER INSERT TRIGGER FIRED'
- INSERT INTO EmployeeTriggerAction(InsertedId,ActionFired) VALUES (@EmpId,'INSERT')
- END
- END
- GO
- INSERT INTO Employee(Name,Salary) VALUES ('Ravi','20000')
- SELECT * FROM Employee
- SELECT * FROM EmployeeTriggerAction
Hope it will be helpful for the beginners.
Guest UserPosted Aug 10, 2018, 3:51 PM
great wrk bro
SubashPosted Mar 13, 2017, 8:31 PM
Very simple and good explanation
Gagan SharmaPosted Nov 4, 2016, 12:26 AM
Thanks for sharing ...very useful for me
Raja TPosted Aug 7, 2016, 6:17 AM
Good..
Bhuvan PandeyPosted Aug 5, 2016, 8:18 AM
Good work
Ritesh SinghPosted Aug 5, 2016, 6:09 AM
Nice