Thursday, 7 July 2011

Magic table in sql

The tables "INSERTED" and "DELETED" are called magic tables of the SQL Server. 
We can not see these tables in the data base.But we can access these tables from the "TRIGGER".
When we insert the record into the table, the magic table"INSERTED" will be created 
In that table the current inserted row will be available. We can access this record in the 
"TRIGGER".
When we delete the record from the table, the magic table "DELETED" will be created
In that table the current deleted row will be available. We can access this record in the
"TRIGGER".
When we update the record from the table, the both magic table will be created. old values insert in "DELETED" table and new values insert in "INSERTED" table. We can access both record through the "TRIGGER".
Example :
Create the tables :
create table LOGTABLE (UserId nvarchar(100),Message nvarchar(100),Mode nvarchar(50))
create table tblAccountDetail(Acc_id int,Acc_Code nvarchar(100),Acc_Name nvarchar(100))
Create insert trigger
create TRIGGER LogMessage_Insert
ON tblAccountDetail
FOR INSERT
AS
   DECLARE @Code varchar(50)
   DECLARE @NAME varchar(50)
   SELECT @Code= Acc_code,@NAME =Acc_Name  FROM INSERTED
   INSERT INTO LOGTABLE(UserId,Message,Mode) values (@Code,@NAME,'Insert')
GO
create update trigger
create trigger logMessage_Update
on tblAccountDetail
for update
as 
   DECLARE @Code varchar(50)
   DECLARE @NAME varchar(50)
   SELECT @Code= Acc_code,@NAME =Acc_Name  FROM INSERTED
   INSERT INTO LOGTABLE(UserId,Message,Mode) values (@Code,@NAME,'Update New')   
   
   DECLARE @Code1 varchar(50)
   DECLARE @NAME1 varchar(50)
   SELECT @Code1= Acc_code,@NAME1 =Acc_Name  FROM DELETED
   INSERT INTO LOGTABLE(UserId,Message,Mode) values (@Code1,@NAME1,'Update Old')
GO
create delete trigger
CREATE TRIGGER LogMessage_Delete
ON tblAccountDetail
FOR DELETE
AS
   DECLARE @Code varchar(50)
   DECLARE @NAME varchar(50)
   SELECT @Code= Acc_code,@NAME =Acc_Name  FROM DELETED
   INSERT INTO LOGTABLE(UserId,Message,Mode) values (@Code,@NAME,'Delete')
GO
///////////////
insert into tblAccountDetail values(1,'Code-1','Name-1')
in this case trigger will auto fired and insert new row in LOGTABLE table 
select from the magic tables "INSERTED"

No comments:

Post a Comment