Mladen Prajdić Blog

Blog about stuff and things and stuff. Mostly about SQL server and .Net

SQL Server 2005 Output Clause

I ran into this little gem today while doing some deletes and forgeting Delete syntax :)))
There is now Output clause for DELETE, INSERT and UPDATE statements.
It outputs the affected rows into a table variable, a simple resultset or into a table.
I guess auditing is possible this way too now.

Example:

create table test(id int identity(1,1), name varchar(100))
insert into test (name)
select 'name 1' union all select 'name 2' union all select 'name 3' union all 
select 'name 4' union all select 'name 5' union all select 'name 6' union all 
select 'name 7' union all select 'name 8' union all select 'name 9' union all 
select 'name 10' union all select 'name 11' union all select 'name 12' 
go
select * from test
declare @deleted table (id int, name varchar(100))
delete test
output DELETED.* into @deleted
where id < 5
select * from @deleted
delete test
output DELETED.*
where id between 5 and 10
select * from test
go
drop table test

More info in BOL under OUTPUT Clause

Legacy Comments


Jeff
2006-06-08
re: SQL Server 2005 Output Clause
very cool ...I've done lots of reading about SQL 2005 and this is the first I've seen on this! Good find, this might be pretty handy ..

Andrej Tozon
2006-06-08
re: SQL Server 2005 Output Clause
yeah... this option can also come in handy when having to output inserted identity column values.

bahskar
2008-03-26
re: SQL Server 2005 Output Clause
Hi
i am facing one problem how to delete duplicate rows from the tables