Friday, December 20, 2013

Output Clause in SQL 2005 / 2008 / 2012

SQL Server 2005 and above has new Output clause.
This is very help to create a copy of what is inserted / updated / deleted.
Output clause has an access to inserted and deleted tables (like triggers) and the data can be copied to
table variable / temp table / permanent table.

Lets see an example:

Note: Table variable declaration need to be selected while running query.

Example using Insert statement:

create table customer (name varchar(100), joindate date)
go

declare @customer table (name varchar(100), joindate date)

-- Insert into table and also output to table variable
insert into customer (name, joindate)
output inserted.name, inserted.joindate into @customer 
values ('John', '01/01/2012')

-- check results
select * from customer 
select * from @customer 


No comments: