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';
IF EXISTS(SELECT *FROM DELETED)
BEGIN
SET @action=
CASE
WHEN EXISTS(SELECT * FROM INSERTED) THEN 'UPDATE'
ELSE 'DELETE'
END
END
ELSE
IF NOT EXISTS(SELECT *FROM INSERTED)RETURN;
IF(@action='INSERT' or @action='UPDATE')
BEGIN
set @Count=(select count(*) from INSERTED)
END
IF @action='DELETE'
BEGIN
set @Count=(select count(*) from INSERTED)
END
IF @action='DELETE'
BEGIN
set @Count=(select count(*) from DELETED)
END
insert into db0.AuditTable
select getdate(),CURRENT_USER,Host_name(),null,@tbName,'dim',@action,@Count
END
GO