问题
I have a trigger that logs on changes to the metadata of tables in a database. it saves the logs in another table called tblMonitorChange. When i rename a table no triggers is generated.
this is the trigger :
USE ReportServer
GO
CREATE TRIGGER trgMonitorChange
ON DATABASE
FOR CREATE_TABLE, ALTER_TABLE, DROP_TABLE , RENAME_TABLE
AS
set nocount on
declare @EventType varchar(100)
declare @SchemaName varchar(100)
declare @ObjectName varchar(100)
declare @ObjectType varchar(100)
SELECT
@EventType = EVENTDATA().value('(/EVENT_INSTANCE/EventType)[1]','nvarchar(max)')
,@SchemaName = EVENTDATA().value('(/EVENT_INSTANCE/SchemaName)[1]','nvarchar(max)')
,@ObjectName = EVENTDATA().value('(/EVENT_INSTANCE/ObjectName)[1]','nvarchar(max)')
,@ObjectType = EVENTDATA().value('(/EVENT_INSTANCE/ObjectType)[1]','nvarchar(max)')
-- Is the default schema used
if @SchemaName = ' ' select @SchemaName = default_schema_name from sys.sysusers u join sys.database_principals p
on u.uid = p.principal_id where u.name = CURRENT_USER
insert into tblMonitorChange
select @EventType, @SchemaName, @ObjectName, @ObjectType, getdate(), SUSER_SNAME()
this is a sample output on 1) creating TestTable, 2)renaming it to TestTable2 and then 3) adding a column to it.
EventType SchemaName ObjectName ObjectType EventDate
CREATE_TABLE dbo TestTable TABLE 2017-11-01 10:55:44.590
ALTER_TABLE dbo TestTable2 TABLE 2017-11-01 14:36:07.543
But renaming has not been logged.
So how can i monitor renaming the table?
Any help would be appreciated.
回答1:
Can you replace Rename_table event with RENAME event? Below Codes working properly
CREATE TRIGGER ddl_trigger_alter ON DATABASE
WITH EXECUTE AS 'dbo'
FOR CREATE_TABLE, ALTER_TABLE, DROP_TABLE,RENAME
AS
DECLARE @ddltriggerxml XML;
SELECT @ddltriggerxml = EVENTDATA();
SELECT @ddltriggerxml;
GO
CREATE TABLE TEST(ID INT)
go
sp_rename 'test_new','test'
来源:https://stackoverflow.com/questions/47055049/monitor-renaming-a-table-in-a-sql-server-database-with-trigger