首页 > 代码库 > SQL Server - 使用表触发器记录表插入,更新,删除行数

SQL Server - 使用表触发器记录表插入,更新,删除行数

除了表触发器的基本知识,本篇还使用了一下知识点。

  1.    如何使用sql获取当前session 用户名和机器名

Select CURRENT_USER,Host_name()

  2.    如何在表触发器中获取当前表名称

SELECT OBJECT_SCHEMA_NAME( parent_id ) + ‘.‘ + OBJECT_NAME( parent_id )  FROM sys.triggers

 

触发器完整代码

ALTER TRIGGER dbo.DimTest_AdutitTriger
   ON  dbo.DimTest
   AFTER INSERT,DELETE,UPDATE
AS
BEGIN
                SET NOCOUNT ON;
                declare @tbName varchar(256)
                SELECT @tbName = ‘dbo.DimTest’
                DECLARE @action as varchar(20), @Count int = 0 ;
    SET @action = ‘INSERT‘; -- Set Action to Insert by default.

    IF EXISTS(SELECT * FROM DELETED)
    BEGIN
        SET @action =
            CASE
                WHEN EXISTS(SELECT * FROM INSERTED) THENUPDATE-- Set Action to Updated.
                ELSEDELETE-- Set Action to Deleted.      
            END
    END
    ELSE
        IF NOT EXISTS(SELECT * FROM INSERTED) RETURN; -- Nothing updated or inserted.
                IF ( @action = ‘INSERTor @action =‘UPDATE‘)
                BEGIN
                                set @Count = (select count(*) from INSERTED)
                END
                IF  @action = ‘DELETEBEGIN
                                set @Count = (select count(*) from DELETED)
                END
                insert into dbo.AuditTable
                select getdate(),CURRENT_USER,Host_name(),null,@tbName,‘dim‘,@action,@Count
END
GO

SQL Server - 使用表触发器记录表插入,更新,删除行数