SQL Server 2014,触发器:如何迭代已删除的行?

时间:2017-03-29 08:24:55

标签: sql-server sql-server-2008

注意!使用触发器对我来说是必要的!我执行以下任务所需的唯一方法是使用触发器!

问题是 - 我需要一个触发器,在某个表中删除rowS时会调用它。事物触发必须做 - 迭代每个被删除的 行,并执行一些代码 - 取决于当前迭代的行值。

例如,我做了这个触发器,当我删除一行时,它就有效 按命令

DELETE FROM books WHERE id=5

触发器在这里:

GO
CREATE TRIGGER onBookDelete ON books
INSTEAD OF DELETE
AS
DECLARE @book_id int
BEGIN

    SET NOCOUNT ON;

    SELECT id FROM deleted
    SET @book_id = (SELECT id FROM deleted)
    PRINT @book_id
    BEGIN 
         DELETE FROM "books-topics" WHERE book_id=@book_id
         DELETE FROM "books-genres" WHERE book_id=@book_id
         DELETE FROM books WHERE id=@book_id
    END
END;

所以,我想要实现的目标是创建具有相同任务的触发器, 但是当我一次删除多行时它必须工作,例如

 DELETE FROM books WHERE id=5 OR id=3 OR id=8

同一个任务我的意思是,例如,在每个已删除的行上调用以下代码

DELETE FROM "books-topics" WHERE id=DELETEDROW.book_id
DELETE FROM "books-genres" WHERE id=DELETEDROW.book_id 
DELETE FROM books WHERE id=DELETEDROW.book_id

1 个答案:

答案 0 :(得分:1)

您的老师应该考虑更好的示例而不是删除触发器。这个问题首先出现在删除级联上。

但是,由于你的任务是使用触发器,我会建议这样的事情:

CREATE TRIGGER onBookDelete ON books
INSTEAD OF DELETE
AS
BEGIN

    SET NOCOUNT ON;

    BEGIN TRASACTION
    BEGIN TRY
        DELETE bt
        FROM "books-topics" bt
        INNER JOIN deleted d ON bt.book_id= d.book_id

        DELETE bg
        FROM "books-genres" bg
        INNER JOIN deleted d ON bg.book_id= d.book_id

        DELETE b
        FROM books b
        INNER JOIN deleted d ON b.book_id= d.book_id

        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
    END CATCH
END;