English 中文(简体)
SQL Server: Can I set a trigger on ALTERing a stored proc?
原标题:

Everytime a stored proc is ALTERed or CREATEd, I want to capture that in a trigger to do some stuff afterwards.

Can I do that in SQL Server 2008?

Thank you. --Beemer

最佳回答

If you want to do somethin withing the ALTER/CREATE/DROP context (ie. inside the same transaction) and even prevent the ALTER/CREATE/DROP then you should look into DDL Triggers.

If you want to do something after the ALTER/CREATE/DROP , in a separate transaction, and have the liberty to do some lengthy processing without slowing down the original DDL, then you should look into Event Notifications.

Note that Event Notifications can actually be delivered remotely so you can capture all DDL events from an entire corporate group into one single central repository.

问题回答
CREATE TRIGGER tddl_storedprocevents ON DATABASE
FOR
CREATE_PROCEDURE,ALTER_PROCEDURE,DROP_PROCEDURE
AS
INSERT INTO AUDIT_TABLE(EventType, SQLCommand, etc)
  SELECT EVENTDATA().value( (/EVENT_INSTANCE/EventType)[1] ,  nvarchar(512) )
       , EVENTDATA().value( (/EVENT_INSTANCE/TSQLCommand)[1] ,  nvarchar(max) )
             , etc

/*
EVENTDATA()

SELECT EVENTDATA().value( (/EVENT_INSTANCE/EventType)[1] ,  nvarchar(512) )
     , EVENTDATA().value( (/EVENT_INSTANCE/PostTime)[1] ,  datetime )
     , EVENTDATA().value( (/EVENT_INSTANCE/SPID)[1] ,  nvarchar(4) )
     , EVENTDATA().value( (/EVENT_INSTANCE/ServerName)[1] ,  nvarchar(512) )
     , EVENTDATA().value( (/EVENT_INSTANCE/LoginName)[1] ,  nvarchar(512) )
     , EVENTDATA().value( (/EVENT_INSTANCE/LoginType)[1] ,  nvarchar(512) )
     , EVENTDATA().value( (/EVENT_INSTANCE/SID)[1] ,  nvarchar(512) )
     , EVENTDATA().value( (/EVENT_INSTANCE/ClientHost)[1] ,  nvarchar(512) )
     , EVENTDATA().value( (/EVENT_INSTANCE/IsPooled)[1] ,  nvarchar(1) )
etc
*/

DROP TRIGGER tddl_storedprocevents ON DATABASE

I recommend reading the documentation about the xml object returned by the EVENTDATA(), if you didn t do it by now.

Hope it helps.





相关问题
Export tables from SQL Server to be imported to Oracle 10g

I m trying to export some tables from SQL Server 2005 and then create those tables and populate them in Oracle. I have about 10 tables, varying from 4 columns up to 25. I m not using any constraints/...

SQL server: Can NT accounts be mapped to SQL server accounts

In our database we have an SQL server account that has the correct roles to access some of the databases. We are now switching to windows authentication and I was wondering if we can create a NT user ...

SQL Server 2000, ADO 2.8, VB6

How to determine if a Transaction is active i.e. before issuing Begin Transaction I want to ensure that no previous transaction are open.. the platform is VB6, MS-SQL Server 2000 and ADO 2.8

热门标签