sql-server SQL触发器检测到已更新或已删除

xv8emn3q  于 2022-10-31  发布在  其他
关注(0)|答案(3)|浏览(160)

这是我创建触发器的代码

CREATE TRIGGER TRIGGERNAME ON [TABLENAME]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
     --[SQL STATEMENTS]
END

在SQL语句中,如何检查以下内容:

if (a row is updated) {
    -- do something
} 
else if (a row is deleted) {
    -- do something else
}
5gfr0r5j

5gfr0r5j1#

CREATE TRIGGER [TRIGGERNAME] ON [TABLENAME]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
    DECLARE @DELETED INT, @UPDATED INT
    SELECT @DELETED = COUNT(*) FROM [deleted]
    SELECT @UPDATED = COUNT(*) FROM [inserted]
    IF @UPDATED > 0
            PRINT ' inserted  '
        END
    ELSE IF @DELETED > 0
        BEGIN
            PRINT ' deleted '
        END
END
gcxthw6b

gcxthw6b2#

在oracle中,您可以这样写
在开始插入、更新、删除之后,在[TABLENAME]上创建触发器[TRIGGERNAME]

IF INSERTING    THEN
-- Some business logic

END IF;

IF UPDATING    THEN
-- Some business logic
END IF;

IF DELETING    THEN
-- Some business logic
END IF;

结束

u4vypkhs

u4vypkhs3#

实际上,触发器仅用于插入/删除:

IF EXISTS (SELECT 1 FROM inserted)
   -- I am an insert
ELSE
   -- I am a delete

但是如果你想创建更新和删除操作的触发器,你可以尝试这样做:

CREATE TRIGGER [TRIGGERNAME] ON [TABLENAME]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
    IF EXISTS (SELECT 1 FROM inserted)
    BEGIN
      IF EXISTS (SELECT 1 FROM deleted)
      BEGIN
        PRINT 'I am an update'
      END
    END
    ELSE
    BEGIN
      PRINT 'I am a delete'
    END
END

您可以查看this reference以获得更多帮助。

相关问题