-1

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

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

BEGIN

END

如何检查它是否是触发器内的更新命令?

阿伦

4

5 回答 5

1

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

…………………………………………………………………………………………………………

于 2013-01-30T09:52:22.990 回答
1

在一个表中创建一个INSERT, UPDATE,DELETE

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;
于 2013-01-30T09:58:47.703 回答
1

在更新触发器中运行的“表”仍称为insertedand deleted,行的旧值在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
于 2013-01-30T10:00:20.340 回答
0

一旦你更新了你的触发器(如 Mitch所说)也适用于UPDATEs,你需要首先检查更新:

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

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

于 2013-01-30T10:00:13.957 回答
0

我要感谢“SWeko”提供的线索。

现在,这就是我所做的并且触发器起作用了。

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
于 2013-01-30T10:20:58.050 回答