Sql Server触发器。触发器如何检查Update Command?

时间:2013-01-30 09:50:51

标签: sql sql-server-2008

我有一个审计购买和销售表的触发器。 INSERT和DELETE是触发器。要检查其是否为“插入”,条件为

IF (SELECT COUNT(*) FROM INSERTED) > 0

BEGIN

END

如何检查Trigger中的Update命令?

阿伦

5 个答案:

答案 0 :(得分:1)

INSERT,DELETE触发器不会触发更新。

.........................

答案 1 :(得分:1)

在一个表格中创建INSERTUPDATEDELETE

IF @@ROWCOUNT = 0

BEGIN
   RETURN;
END;

IF EXISTS(SELECT * FROM inserted)
    BEGIN
      IF EXISTS(SELECT * FROM deleted)
          BEGIN
             -- for UPDATE
          END
      ELSE
          BEGIN
             -- for INSERT
          END
    END
ELSE
    BEGIN
      -- for DELETE
    END;

答案 2 :(得分:1)

更新触发器中正在播放的“表格”仍称为inserteddeleted,并且行的旧值位于deleted表中,而新的值在inserted表中。

您可以使用这些行中的逻辑来检测您是在插入,更新还是删除:

CREATE TRIGGER MyTrigger
   ON  MyTable
   AFTER INSERT,DELETE,UPDATE -- you need to add the "update" here, 
                              -- in order to catch updates as well
AS 
BEGIN
    Declare @insertedCount int
    Declare @deletedCount int
    select @insertedCount = COUNT(*) from inserted
    select @deletedCount = COUNT(*) from deleted
    if (@insertedCount != 0) -- we have some new values
      if (@deletedCount = 0)  -- do we have old values?
        print 'Inserting'
      else 
        print 'Updating'
    else
      print 'Deleting'

END

答案 3 :(得分:0)

一旦您更新了触发器(作为Mitch says)也适用于UPDATE,您需要先检查更新:

IF EXISTS(select * from inserted) and EXISTS(select * from deleted)
BEGIN
   --Update
END

请注意,我已切换到EXISTS而不是COUNT(*)。存在更恰当地描述了我们想要建立的内容 - 表中存在行。我们不关心那里有多少行。

答案 4 :(得分:0)

我想感谢“SWeko”的线索。

现在,这就是我所做的和Trigger的工作。

CREATE TRIGGER dbo.Sample
  ON TableName
  FOR INSERT, UPDATE, DELETE
AS
IF (SELECT COUNT(*) FROM INSERTED) > 0
BEGIN 
   IF (SELECT COUNT(*) FROM DELETED) > 0
       BEGIN
          -- UPDATE (TABLE). 
       END
   ELSE
       BEGIN
          -- INSERT (TABLE).
       END
END
ELSE
   -- DELETE (TABLE).
   BEGIN 
   END