SQL Server - 使用表触发器记录表插入,更新,删除行数
Posted BI Information
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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) THEN ‘UPDATE‘ -- Set Action to Updated. ELSE ‘DELETE‘ -- Set Action to Deleted. END END ELSE IF NOT EXISTS(SELECT * FROM INSERTED) RETURN; -- Nothing updated or inserted. IF ( @action = ‘INSERT‘ or @action =‘UPDATE‘) BEGIN set @Count = (select count(*) from INSERTED) END IF @action = ‘DELETE‘ BEGIN 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 - 使用表触发器记录表插入,更新,删除行数的主要内容,如果未能解决你的问题,请参考以下文章