SQL Server: Move Data to a Different Table using OUTPUT clause

Suppose you want to move some data from one table to another table and then delete the data from source table. In versions prior to SQL Server 2005, this is done in two steps.

1. Copy to target table
2. Delete from source table

In versions from SQL Server 2005/2008 onwards, you can use OUTPUT clause to do this:

Consider the following examples

sql-server-move-table

Now check the output from these tables

select * from @table1
select * from @table2


@table1 has three rows and @table2 has zero rows.

Let us assume that you want to copy data from @table1 where id is 1 or 2, to @table2 and then delete those rows from @table1. You can use the following code:

delete from @table1
output deleted.* into @table2
where cust_id in (1,2)


As soon as rows are deleted from @table1, they are first moved to the DELETED internal table. The code shown above copies this data to @table2

Run the SELECT command again and you can see that the data was moved.

select * from @table1
select * from @table2


sql-server-move-data


About The Author

Madhivanan,an MSc computer Science graduate from Chennai-India, works as a works as a Lead Subject Matter Expert at a company that simplifies BIG data. He started his career as a developer working with Visual Basic 6.0, SQL Server 2000 and Crystal Report 8. As years went by, he started working more on writing queries in SQL Server. He now has good level of knowledge in SQLServer, Oracle, MySQL and PostgreSQL as well. He is also one of the leading posters at www.sqlteam.com and a moderator at www.sql-server-performance.com. His T-sql blog is at http://beyondrelational.com/blogs/madhivanan

3 comments:

Vishal said...

just a small correction, OUTPUT was introduced in 2005 :)

Suprotim Agarwal said...

Thank you Vishal! The post has been updated.

Anonymous said...

Is using the OUTPUT clause "better" than copy and delete? If so, in what ways?

Is it safer? Is it possible for the delete to succeed, but the OUTPUT to fail?

Is it faster? Does it take less resources?