Wednesday, January 15, 2014

OUTPUT clause in SQL Server to access temp tables at the time of INSERT, UPDATE, DELETE, MERGE like Trigger

Reference :
1. http://technet.microsoft.com/en-us/library/ms177564.aspx
2. http://blog.sqlauthority.com/2007/10/01/sql-server-2005-output-clause-example-and-explanation-with-insert-update-delete/

Concept : 
While executing INSERT UPDATE DELETE or MERGE statement you can access temp tables- Inserted and Deleted just like trigger. This can be executed from code to get just deleted items or inserted item, you can get the no of rows affected from there.
Inserted and Deleted tables are creating on the fly at the time of execution of statement in memory, after commit of execution those tables also get deleted.

Example [from: http://technet.microsoft.com/en-us/library/ms177564.aspx]:

USE tempdb;
GO

CREATE TABLE dbo.table1
(
    id INT,
    employee VARCHAR(32)
)
go

INSERT INTO dbo.table1 VALUES 
      (1, 'Fred')
     ,(2, 'Tom')
     ,(3, 'Sally')
     ,(4, 'Alice');
GO

DECLARE @MyTableVar TABLE
(
    id INT,
    employee VARCHAR(32)
);

PRINT 'table1, before delete' 
SELECT * FROM dbo.table1;

DELETE FROM dbo.table1
OUTPUT DELETED.* INTO @MyTableVar
WHERE id = 4 OR id = 2;

PRINT 'table1, after delete'
SELECT * FROM dbo.table1;

PRINT '@MyTableVar, after delete'
SELECT * FROM @MyTableVar;

DROP TABLE dbo.table1;

--Results
--table1, before delete
--id          employee
------------- ------------------------------
--1           Fred
--2           Tom
--3           Sally
--4           Alice
--
--table1, after delete
--id          employee
------------- ------------------------------
--1           Fred
--3           Sally
--@MyTableVar, after delete
--id          employee
------------- ------------------------------
--2           Tom
--4           Alice
 

No comments:

Post a Comment