简体   繁体   English

如何使用多个触发器?

[英]How to use multiple triggers?

DROP TRIGGER IF EXISTS N2Trigger


CREATE TRIGGER N2Trigger 
ON dbo.Date
FOR INSERT, DELETE 
AS 
BEGIN 
    SELECT 'Inserted Datebase' as MESSAGE
    SELECT 'Deleted Database' as MESSAGE
END

DELETE FROM dbo.[Date] WHERE ID = 1 

Here is my code I just want when I use insert statement return 'Inserted Datebase' as MESSAGE这是我在使用插入语句时只想要的代码 return 'Inserted Datebase' as MESSAGE

When I use delete statement return 'Deleted Database' as MESSAGE当我使用删除语句返回“已删除数据库”作为 MESSAGE

The easiest way to check what action fired the trigger is to inspect the inserted and deleted pseudo-tables.检查触发触发器的操作的最简单方法是检查inserteddeleted的伪表。 If the trigger is only on DELETE / INSERT and not on update, then the logic is simply:如果触发器仅在DELETE / INSERT而不是更新时,那么逻辑很简单:

CREATE TRIGGER dbo.trFlarb ON dbo.flarb
  FOR INSERT, DELETE
  AS
  BEGIN
    IF EXISTS (SELECT 1 FROM inserted)
    BEGIN
      SELECT 'Inserted.';
    END

    IF EXISTS (SELECT 1 FROM deleted)
    BEGIN
      SELECT 'Deleted.';
    END
  END

Now, of course, Marc is right: triggers aren't for returning or printing output.现在,当然,Marc 是对的:触发器不是用于返回或打印 output。 This is just a demonstration that you can use those checks to then perform whatever logic you need to perform in the event of either action.这只是一个演示,您可以使用这些检查来执行在任一操作时需要执行的任何逻辑。

That said, if you have two distinctly different things you want to do depending on whether it's an insert or a delete, why not just create two separate triggers?也就是说,如果您有两件截然不同的事情要做,具体取决于它是插入还是删除,为什么不创建两个单独的触发器呢?

CREATE TRIGGER dbo.tr_I_Flarb ON dbo.flarb
  FOR INSERT
  AS
  BEGIN
      SELECT 'Inserted.';
  END
GO

CREATE TRIGGER dbo.tr_D_Flarb ON dbo.flarb
  FOR DELETE
  AS
  BEGIN
      SELECT 'Deleted.';
  END
GO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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