SQL创建DDL触发器

当服务器或数据库中发生数据定义语言(DDL)事件时将被调用。如CREATE,ALTER,DROP等操作。如果要执行以下操作,可以使用DDL触发器:

防止对数据库架构进行更改
希望数据库中发生某些情况以响应数据库架构中的更改
要记录数据库架构中的更改或事件

USE [XXHIS_KF]
GO

/****** Object: DdlTrigger [DDL_LOG] Script Date: 09/12/2017 20:31:28 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

create trigger [DDL_LOG] on database
for DDL_DATABASE_LEVEL_EVENTS
as
begin
set nocount on;
declare @EventTxt xml,@EventType varchar(50)=’’,@Parame varchar(50)=’’,
@SchemaName varchar(30)=’’,@ObjType varchar(50)=’’,
@ObjName varchar(100)=’’,@SqlText varchar(max)=’’,
@SqlTexts varchar(max)=’’,@SText varchar(max)=’’;
set @EventTxt=eventdata();

;with tab as(
select
@EventTxt as xmls
)
select
@EventType= xmls.value(’(/EVENT_INSTANCE/EventType)[1]’ ,‘varchar(50)’ ) ,
@SchemaName=xmls.value(’(/EVENT_INSTANCE/SchemaName)[1]’ ,‘varchar(30)’ ) ,
@ObjType= xmls.value(’(/EVENT_INSTANCE/ObjectType)[1]’ ,‘varchar(50)’ ) ,
@ObjName= xmls.value(’(/EVENT_INSTANCE/ObjectName)[1]’ ,‘varchar(100)’) ,
@Parame = xmls.value(’(/EVENT_INSTANCE/Parameters)[1]’ ,‘varchar(100)’) ,
@SqlText=xmls.value(’(/EVENT_INSTANCE/TSQLCommand)[1]’,‘varchar(max)’)
from tab;
if @ObjName in(‘Proc_Version_Script’,‘DDL_RenameTrigger’,‘DDL_RenameTrigger’)
begin
–set @ObjName=‘不能对’+@ObjName+‘对象进行操作’;
– RAISERROR (@ObjName, 16,1);
–Proc_Version_Script
return;
end;
if @EventType in(‘Create_View’ ,‘Alter_View’ ,‘Drop_View’,
‘Create_Trigger’ ,‘Alter_Trigger’ ,‘Drop_Trigger’,
‘Create_Table’ ,‘alter_table’ ,‘Drop_Table’,
‘Create_Function’ ,‘Alter_Function’ ,‘Drop_Function’,
‘Create_Procedure’ ,‘Alter_Procedure’ ,‘Drop_procedure’,
‘Create_Synonym’ ,‘Drop_Synonym’,
‘CREATE_INDEX’ ,‘ALTER_INDEX’ ,‘DROP_INDEX’
)
insert into DDL_LOG
(EventType,SchemaName,ObjType,ObjName,ExecDate,Terminal)
select @EventType,@SchemaName,@ObjType,@ObjName,SYSDATETIME(),host_name();
end;

GO

SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO

DISABLE TRIGGER [DDL_LOG] ON DATABASE
GO

ENABLE TRIGGER [DDL_LOG] ON DATABASE
GO

你可能感兴趣的:(数据库)