Moving deleted rows from one table to another table (has the triggers as well) using ms sql
I have two tables called Active_QC1(id, req_name, req_type)
and Deleted_QC1(id, req_name, req_type)
. In case I delete data from the Active_QC1
table, that data should move to the Deleted_QC1
table. Both tables can have triggers.
Can anyone guide me with this?
You can use the OUTPUT clause (microsoft.com) in a DELETE statement. The basic outline for a simple delete statement would be something as follows:
DELETE FROM Active_QC1
OUTPUT DELETED.* INTO Deleted_QC1
WHERE id=5;
What it does is delete all rows in Active_QC1
with id=5
, then inserts those rows into Deleted_QC1
.
An example:
CREATE TABLE #Active_QC1(id INT, req_name VARCHAR(128), req_type INT);
CREATE TABLE #Deleted_QC1(id INT, req_name VARCHAR(128), req_type INT);
INSERT INTO #Active_QC1(id,req_name,req_type)
VALUES
(1,'engage',3),
(2,'forward',5),
(3,'obliterate',3),
(4,'reply',5),
(5,'delete',5);
DELETE FROM
#Active_QC1
OUTPUT
DELETED.id,
DELETED.req_name,
DELETED.req_type
INTO
#Deleted_QC1(id,req_name,req_type)
WHERE
req_type=5;
SELECT*FROM #Deleted_QC1;
DROP TABLE #Deleted_QC1;
DROP TABLE #Active_QC1;
This script makes two temporary tables #Active_QC1
and #Deleted_QC1
with identical table definitions. Some rows are added to #Active_QC1
. The DELETE
statement deletes all rows in #Active_QC1
with req_type=5
, and inserts them into #Deleted_QC1
. The script finally selects all rows in #Deleted_QC1
. The result is the following:
╔════════╦══════════╦══════════╗
║ id ║ req_name ║ req_type ║
╠════════╬══════════╬══════════╣
║ 2 ║ forward ║ 5 ║
║ 4 ║ reply ║ 5 ║
║ 5 ║ delete ║ 5 ║
╚════════╩══════════╩══════════╝