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

3 comments:

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

    ReplyDelete
  2. Thank you Vishal! The post has been updated.

    ReplyDelete
  3. 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?

    ReplyDelete