MSSQL触发器如何判断,增删改事件,给个demo
时间: 2024-01-10 12:02:49 浏览: 84
好的,下面是一个简单的MSSQL触发器示例,演示如何判断增删改事件:
```
CREATE TRIGGER MyTrigger
ON MyTable
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
IF EXISTS(SELECT * FROM inserted) AND EXISTS(SELECT * FROM deleted)
BEGIN
-- Update event
PRINT 'Update event occurred'
END
ELSE IF EXISTS(SELECT * FROM inserted)
BEGIN
-- Insert event
PRINT 'Insert event occurred'
END
ELSE IF EXISTS(SELECT * FROM deleted)
BEGIN
-- Delete event
PRINT 'Delete event occurred'
END
END
```
在此示例中,触发器被绑定到名为MyTable的表上,并在插入、更新或删除操作后触发。在触发器主体内,它首先检查Inserted和Deleted表是否都存在,以确定是否为更新事件。如果是,则打印“Update event occurred”消息。如果只存在Inserted表,则表示为插入事件,打印“Insert event occurred”消息。如果只存在Deleted表,则表示为删除事件,打印“Delete event occurred”消息。通过这种方式,可以轻松地确定触发器的事件类型,并相应地执行操作。
阅读全文