I think you are looking for what unofficially called magic tables
in SQL server.
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 update a record on the table where trigger is created, the magic tables "INSERTED
" and "DELETED
" both will be created, the Old data of the updating record will be available in "DELETED" table and, the new data will be available in "INSERTED" table, while accessing them inside 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
".
Example:
Following code Explains the magic table "INSERTED
":
CREATE TRIGGER LogMessage
ON EMP
FOR INSERT
AS
DECLARE @EMPNAME varchar(50)
SELECT @EMPNAME= (SELECT EMPNAME FROM INSERTED)
INSERT INTO LOGTABLE(UserId,Message) values (@EMPNAME,'Record Added')
GO
Following code Explain the magic table "DELETED
"
CREATE TRIGGER LogMessage
ON EMP
FOR DELETE
AS
DECLARE @EMPNAME varchar(50)
SELECT @EMPNAME= (SELECT EMPNAME FROM DELETED)
INSERT INTO LOGTABLE(UserId,Message) values (@EMPNAME,'Record Removed')
GO
Sources(All credit to these articles & authors):
http://www.codeproject.com/Questions/285423/what-is-magic-table-different-types-of-magic-table
http://www.dotnetspider.com/resources/29332-Magic-tables-SQL-Server.aspx
.
.
Alternatively
, you can try:
Obtaining Changes by Using the Change Tracking Functions, its MSDN link to explain how
to track changes by using in-built functions.
CHANGETABLE(CHANGES …)
function
This rowset function is used to query for change information. The function queries the data stored in the internal change tracking tables. The function returns a results set that contains the primary keys of rows that have changed together with other change information such as the operation, columns updated and version for the row.
CHANGE_TRACKING_CURRENT_VERSION()
function
Is used to obtain the current version that will be used the next time when querying changes. This version represents the version of the last committed transaction.
CHANGE_TRACKING_MIN_VALID_VERSION()
function
Is used to obtain the minimum valid version that a client can have and still obtain valid results from CHANGETABLE(). The client should check the last synchronization version against the value thatis returned by this function. If the last synchronization version is less than the version returned by this function, the client will be unable to obtain valid results from CHANGETABLE() and will have to reinitialize.
Refer syntax & usage at http://technet.microsoft.com/en-us/library/cc280358%28v=sql.105%29.aspx
Hope it helps.