SQL Server Trigger switching Insert,Delete,Update

两盒软妹~` 提交于 2019-12-03 07:30:56

I will show you a simple way to check this in SQL Server 2000 or 2005 (you forgot to mention which version you are using), but in general I agree with Remus that you should break these up into separate triggers:

DECLARE @i INT, @d INT;
SELECT @i = COUNT(*) FROM inserted;
SELECT @d = COUNT(*) FROM deleted;
IF @i + @d > 0
BEGIN
    IF @i > 0 AND @d = 0
    BEGIN
        -- logic for insert
    END

    IF @i > 0 AND @d > 0
    BEGIN
        -- logic for update
    END

    IF @i = 0 AND @d > 0
    BEGIN
        -- logic for delete
    END
END

Note that this may not be perfectly forward-compatible due to the complexity MERGE introduces in SQL Server 2008. See this Connect item for more information:

So if you are planning to use SQL Server 2008 and MERGE in the future, then this is even more reason to split the trigger up into a trigger for each type of DML operation.

(And if you want more reasons to avoid MERGE, read this.)

You can use the inserted and deleted tables to see what changes were made to the table.

For an UPDATE, the deleted table contains the old version of the row, and inserted the new version.

DELETE and INSERT use their own table as you would expect.

You can have three separate triggers, one for INSERT one for UPDATE one for DELETE. Since each trigger is different, there is no need for switch logic.

Ryan Elkins

I think the general way to do this is to create a trigger for each action, like so:

CREATE TRIGGER INSERT_ON_TABLEA   
ON  TABLEA   
AFTER INSERT 
AS 
BEGIN    
SET NOCOUNT ON;    
-- INSERT ON AUX TABLEB
END
GO

CREATE TRIGGER DELETE_ON_TABLEA   
ON  TABLEA   
AFTER DELETE
AS 
BEGIN    
SET NOCOUNT ON;    
-- DELETE ON AUX TABLEB
END
GO

You can use one trigger for all commands/operations by use union join;

CREATE TRIGGER DML_ON_TABLEA
 ON  TABLEA
AFTER INSERT,DELETE,UPDATE
AS 
BEGIN
    SET NOCOUNT ON;
   --logic for insert
    insert into Backup_table (columns_name) select columns_name from inserted i
    --logic for delete
   UNION ALL
    insert into Backup_table (columns_name) select columns_name from deleted d
END
GO

--note update command like inserted command but have another command deleted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!