除了表触发器的基本知识,本篇还使用了一下知识点。
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
时间: 2024-10-28 19:37:25