Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving delete information to temp tables using into

Tags:

sql

sql-server

Is there a way of using into with delete keyword to save the deleted rows in a temp table in sql server?

like image 605
satyajit Avatar asked Sep 20 '13 13:09

satyajit


People also ask

Which is used to delete data from table?

The DELETE statement is used to delete existing records in a table.

How do I copy data from one table to the temp table in SQL?

INSERT INTO SELECT statement reads data from one table and inserts it into an existing table. Such as, if we want to copy the Location table data into a temp table using the INSERT INTO SELECT statement, we have to specify the temporary table explicitly and then insert the data.

Can you delete from temp table SQL?

Using the DROP TABLE command on a temporary table, as with any table, will delete the table and remove all data. In an SQL server, when you create a temporary table, you need to use the # in front of the name of the table when dropping it, as this indicates the temporary table.


1 Answers

Without using a trigger, the OUTPUT clause lets you do it

-- create if needed
SELECT * INTO #KeepItSafe FROM TheTable WHERE 0 = 1;

--redirect the deleted rows to the temp table using OUTPUT
DELETE TheTable OUTPUT DELETED.* INTO #KeepItSafe WHERE ...;
like image 107
gbn Avatar answered Oct 13 '22 00:10

gbn