The INSERTED and DELETED logical tables that exist in SQL Server and allow for handling the data when information is inserted, updated and deleted in DML Triggers only:
DML trigger statements use two special tables: the deleted table and the inserted tables. SQL Server automatically creates and manages these tables. You can use these temporary, memory-resident tables to test the effects of certain data modifications and to set conditions for DML trigger actions. You cannot directly modify the data in the tables or perform data definition language (DDL) operations on the tables, such as CREATE INDEX. (Books Online, SQL Server 2008).
Below is summary of what special tables get modified with each DML statement.
I wanted to know if there anything special happens when I work with single row versus batch. So I test follow cases …
For testing I Created a new table called ‘IDST_Testing’ (IDST = Inserted Deleted Special Table). Below is summary of test cases and records inserted in each of the special tables.
|Double Insert – Two Statements||1/per statement||1/per statement|
|Double Update – Two Statements||1/per statement||1/per statement|
|Double Delete – Two Statements||1/per statement||1/per statement|
|Batch Insert – Two Records||2||0|
|Batch Update – Two Records||2||2|
|Batch Delete – Two Records||0||2|
All those results are normal; but what was surprising was when I was doing batch INSERTED and DELETED the records were in reverse order.
I inserted following two records:
But when I looked at INSERTED table it showed:
In my actual table it was in order what I entered in but when processing the INSERTED and DELETED table they are revered. It was same in tables with IDENTITY columns and without.
Another interesting information on these tables:
- In SQL Server 2000, these logical tables internally refer to database transaction log to provide data when user queries them.
- In SQL Server 2005, these logical tables are maintained in tempdb and they are maintained using the new technology Row versioning.
- Accessing of logical tables is much faster in SQL Server 2005 when compared to SQL Server 2000 as the load is removed from transaction log and moved to tempdb.
- Logical tables are never indexed. So, if you are going to loop through each and every record available in these tables, then consider copying data of logical tables to temporary tables and index them before looping through.
When creating trigger it is important to keep in mind that sometimes a Batch Import, Update or Delete might happen against the table; if you are referring the logical tables INSERTED and DELETED the data will be in reverse order so you don’t want to cause issues when traversing through these tables in triggers.
Note always keep in mind RBAR when designing triggers; its very easy set up RBAR scenario when working with triggers. For more information on that please read, http://www.simple-talk.com/sql/t-sql-programming/rbar–row-by-agonizing-row/.