简体   繁体   中英

Moving deleted rows from one table to another table (has the triggers as well) using ms sql

I have 2 tables called Active_QC1(id, req_name, req_type) and Deleted_QC1(id, req_name, req_type) , if in case I will delete the data from Active_QC1 table that deleted data should move in to Deleted_QC1 . Both the table can have triggers, can any one guide me on this please?

I will suggest you to add one column to Active_QC1 table that names Status_Flag its varchar type and set status flag 'Y' or 'N' as corresponding to deleted or not. then you can try following queries

Query #1:

ALTER TABLE Active_QC1
ADD Status_Flag VARCHAR2(3 BYTE)

Query #2:

UPDATE Active_QC1
SET Status_Flag = 'Y' 
WHERE id = <deleted records id>

Query #3:

INSERT INTO Deleted_QC1 (id, req_name, req_type)
    SELECT id, req_name, req_type
    FROM Active_QC1
    WHERE Status_Flag = 'Y';

Query #4.

DELETE FROM Active_QC1
WHERE Status_Flag = 'N';

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 ║
╚════════╩══════════╩══════════╝

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM