我有一个审计采购和销售表的触发器。触发器在 INSERT 和 DELETE 上。要检查它是否“插入”,条件是
IF (SELECT COUNT(*) FROM INSERTED) > 0
BEGIN
END
如何检查它是否是触发器内的更新命令?
阿伦
我有一个审计采购和销售表的触发器。触发器在 INSERT 和 DELETE 上。要检查它是否“插入”,条件是
IF (SELECT COUNT(*) FROM INSERTED) > 0
BEGIN
END
如何检查它是否是触发器内的更新命令?
阿伦
INSERT,DELETE 触发器不会触发更新。
…………………………………………………………………………………………………………
在一个表中创建一个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;
在更新触发器中运行的“表”仍称为inserted
and 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
一旦你更新了你的触发器(如 Mitch所说)也适用于UPDATE
s,你需要首先检查更新:
IF EXISTS(select * from inserted) and EXISTS(select * from deleted)
BEGIN
--Update
END
请注意,我已切换到EXISTS
而不是COUNT(*)
. Exists 更恰当地描述了我们想要建立的内容——表中存在行。我们不在乎那里有多少行。
我要感谢“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