SQL Server : trigger on update value with Insert and Delete

56lgkhnf  于 2023-08-02  发布在  SQL Server
关注(0)|答案(1)|浏览(133)

I am newbie in SQL Server.

I have Table A with columns id , name , delete (boolean).

I have another Table B which has the same columns as A.

Once in Table A delete flag becomes 1 (programmatically), I need to insert that row into Table B and remove it from Table A.

So below get the results

  • Table A: Has records with delete -> 0
  • Table B: Has records with delete -> 1

Is it possible to achieve this via triggers?

Referring this also : https://learn.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql?view=sql-server-ver16

bprjcwpo

bprjcwpo1#

In your case, you can create an AFTER DELETE trigger on Table A that inserts the deleted row into Table B and removes it from Table A. Here's an example of how you can create such a trigger:

CREATE TRIGGER trg_DeleteRecord
ON TableA
AFTER DELETE
AS
BEGIN
    SET NOCOUNT ON;

    -- Insert the deleted row into Table B
    INSERT INTO TableB (id, name, delete)
    SELECT id, name, delete
    FROM deleted;

    -- Delete the row from Table A
    DELETE FROM TableA
    FROM deleted
    WHERE TableA.id = deleted.id;
END;

In this trigger, the deleted pseudo-table contains the rows deleted from Table A. You can use it to select the necessary columns and insert them into Table B. Then, you can perform a delete operation on Table A using a join with the deleted table to remove the corresponding rows.

相关问题