sqlserver 表结构变更日志

sqlserver 表结构变更日志

用途

用于自动记录表结构变更日志;

脚本

/*表结构变更日志表*/
CREATE TABLE SYS_DDL_LOG (
	ID INT IDENTITY
	, POSTTIME DATETIME
	, DATABASENAME VARCHAR(50)
	, EVENTTYPE VARCHAR(50)
	, LOGINNAME VARCHAR(50)
	, SERVERNAME VARCHAR(50)
	, USERNAME VARCHAR(50)
	, SCHEMANAME VARCHAR(50)
	, OBJECTNAME VARCHAR(50)
	, OBJECTTYPE VARCHAR(50)
	, TSQL VARCHAR(2000)
	, CONSTRAINT PK_SYS_DDL_LOG PRIMARY KEY(ID)
);
GO 
/*表结构变更触发器*/
CREATE TRIGGER sys_ddl_tri ON DATABASE 
FOR DDL_DATABASE_LEVEL_EVENTS 
AS 
DECLARE @data XML
SET @data = EVENTDATA()
    PRINT 'Login Event Issued.'

	INSERT sys_ddl_log 
   (PostTime,DatabaseName, EventType, LoginName, ServerName, UserName, SchemaName, ObjectName, ObjectType ,TSQL) 
   VALUES 
   (GETDATE(), 
   @data.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'VARCHAR(100)'),
   @data.value('(/EVENT_INSTANCE/EventType)[1]', 'VARCHAR(100)'),
   @data.value('(/EVENT_INSTANCE/LoginName)[1]', 'VARCHAR(100)'), 
   
   @data.value('(/EVENT_INSTANCE/ServerName)[1]', 'VARCHAR(50)'),
   @data.value('(/EVENT_INSTANCE/UserName)[1]', 'VARCHAR(50)'),
   @data.value('(/EVENT_INSTANCE/SchemaName)[1]', 'VARCHAR(50)'),
   @data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'VARCHAR(50)'),
   @data.value('(/EVENT_INSTANCE/ObjectType)[1]', 'VARCHAR(50)'),
   @data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'VARCHAR(2000)')
    ) ;
GO

你可能感兴趣的:(sqlserver)