SQL Server 2012.触发器。如何在创建表时自动创建触发器

时间:2014-01-14 12:32:05

标签: sql stored-procedures triggers ddl audit

我在SQL上有一个触发器。它用于审计表。每当创建新表时,如何将此触发器自动分配给新表? 我会创建一个[ALL] [SERVER]触发器来运行脚本来创建触发器吗? 我知道我将不得不使用IF EXISTS。谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以创建在特定事件中运行的DDL triggers,例如。在数据库中创建表时。例如:

create table audit(table_name sysname, data xml)
go

CREATE trigger on_create_table 
on DATABASE
for CREATE_TABLE
as
begin
    declare @x xml = EVENTDATA();
    declare @tableName sysname, @schemaName sysname, @triggerName sysname;
    set @schemaName = @x.value(N'(/EVENT_INSTANCE/SchemaName)[1]', N'sysname');
    set @tableName = @x.value(N'(/EVENT_INSTANCE/ObjectName)[1]', N'sysname');
    set @triggerName = @tableName + N'_trg';


    declare @sql nvarchar(max);
    set @sql = N'create trigger ' +quotename(@schemaName) + N'.' + quotename(@triggerName) + N' 
    on ' + quotename(@tableName) + N'
    after INSERT
    as 
      set nocount on;
      declare @event xml;
      set @event = (select * from INSERTED for xml auto, type);
      insert into audit (table_name, data) values (' + quotename(@tableName, '''') +N', @event);';
    -- print @sql;
    execute sp_executesql @sql;
end
go

create table t (a int);
go

insert into t (a) values (1)
go

select * from audit;
go