Create a trigger system in SQL Server (Trigger After Insertion )

Rumman Ansari   2019-03-19   Student   SQL SERVER > Create-Trigger-System-in-SQL-server   24812 Share

Trigger after Insertion

Create a trigger system. When the user will insert the data from that data will insert into another table which is reserved for the backup.

Use Database


USE DB02TEST01

This is our primary table where data will refelect


CREATE TABLE Product_1637935(
ProductId int,
ProductName varchar(50),
Price Money
)

This table is used for the backup information


CREATE TABLE ProductLog_1637935(
ProductId int,
ProductName varchar(50),
Price Money,
Track varchar(50),
AuditTime datetime
)

In this below section we are creating a trigger, which will store the data after insertion in the first table.


CREATE TRIGGER TriggerpRODUCT_1637935 ON Product_1637935
AFTER INSERT
AS
BEGIN
DECLARE @ProductId int
DECLARE @ProductName varchar(50)
DECLARE @Price Money
SET @ProductId = (SELECT I.ProductId FROM inserted I)
SET @ProductName = (SELECT I.ProductName FROM inserted I)
SET @Price = (SELECT I.Price FROM inserted I)
INSERT INTO ProductLog_1637935 VALUES (@ProductId, @ProductName, @Price, 'Added', getdate())
END

after this insert command data also intert in the log table (backup table)


INSERT INTO Product_1637935 VALUES(100, 'Rice',100)

See the information on both the table


SELECT * FROM Product_1637935
SELECT * FROM ProductLog_1637935