Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT deleted values into a table before DELETE with a DELETE TRIGGER

For some reason I can't find the exact answer that I need. I searched for at last 20 minutes in here.

I know it's simple. VERY simple. But I can't fire the trigger for some reason..

I have a table with two columns

dbo.HashTags

|__Id_|_name_|
|  1  | Love |

I want to insert the deleted values into another table called dbo.HashTagsArchive on a DELETE query.

Example:

DELETE FROM [dbo].[HashTags] WHERE Id=1

After this example I should have the deleted row in dbo.HashTagsArchive and the row with Id=1 should be deleted in dbo.HashTags

I tried this TRIGGER:

ALTER TRIGGER [dbo].[HashTags_BeforeDelete]
    ON [dbo].[HashTags]
    FOR DELETE
AS
  BEGIN
    INSERT INTO HashTagsArchive
   ( Id,
     HashTagId,
     delete_date)
   SELECT d.Id, m.HashTagId,GETUTCDATE() FROM deleted d 
   JOIN dbo.HashTags m ON m.Id=d.Id
    DELETE FROM dbo.HashTags
    WHERE ID IN(SELECT deleted.Id FROM deleted)
  END
GO

It's getting Deleted but no Inserted row in the HashTagsArchive

like image 405
Ofir Hadad Avatar asked Dec 24 '12 08:12

Ofir Hadad


People also ask

How do you insert values into a table using triggers?

To create a trigger, we need to change the delimiter. Inserting the row into Table1 activates the trigger and inserts the records into Table2. To insert record in Table1. To check if the records are inserted in both tables or not.

How do the inserted and deleted tables work with a DML statement in an for trigger?

The deleted table stores copies of the affected rows in the trigger table before they were changed by a DELETE or UPDATE statement (the trigger table is the table on which the DML trigger runs).

What is a before delete trigger?

Description. A BEFORE DELETE Trigger means that Oracle will fire this trigger before the DELETE operation is executed.


1 Answers

Your problem is: this trigger fires AFTER the delete has already happened. So there is no more row in HashTags which you could join on!

You need to use this trigger instead:

ALTER TRIGGER [dbo].[HashTags_BeforeDelete]
    ON [dbo].[HashTags]
    FOR DELETE
AS
  BEGIN
    INSERT INTO HashTagsArchive(Id, HashTagId, delete_date)
       SELECT 
           d.Id, d.HashTagId, GETUTCDATE() 
       FROM deleted d 
  END
GO

The Deleted pseudo table contains the whole row(s) that were deleted - no need to join on anything...

Also: this trigger fires after the delete has happened - so you don't need to do anything yourself, inside the trigger - just insert those bits of information into your archive table - that's all. Everything else is handled by SQL Server for you.

like image 158
marc_s Avatar answered Oct 12 '22 23:10

marc_s