Run some code when my database is deleted from SQL Server?
I need to delete some text files when a certain database is dropped from SQL server (because they contain associated data that becomes out of date). I had a thought that I could use some sort of trigger to run a query to do that but I can't figure out where to put that or how to do it.
I'm using SQL server 2005 but likely to upgrade as time goes on.
Any ideas?
thanks,
Jamie
Thanks to Martin Smith, here is the code I used:
CREATE TRIGGER ddl_trig_database
ON ALL SERVER
FOR DROP_DATABASE
AS
DECLARE @database_count int
select @database_count=count(*) from sys.databases where name='myDbName'
IF @database_count = 0
BEGIN
-- Our database has been dropped, delete text files
DECLARE @Result int
DECLARE @FSO_Token int
EXEC @Result = sp_OACreate 'Scripting.FileSystemObject', @FSO_Token OUTPUT
EXEC @Result = sp_OAMethod @FSO_Token, 'DeleteFile', NULL, 'D:\afile.txt'
EXEC @Result = sp_OADestroy @FSO_Token
END
I also had开发者_JAVA技巧 to run this to enable the OLE Automation delete:
exec sp_configure
go
exec sp_configure 'Ole Automation Procedures', 1
-- Configuration option 'Ole Automation Procedures' changed from 0 to 1.
go
reconfigure
go
You need a Server scoped DDL trigger for this I think. I'm not really sure off the top of my head how you would delete text files in TSQL though. Looks like there's some ideas here. Or maybe you could invoke an SSIS package from the trigger that does the clean up.
CREATE TRIGGER ddl_trig_database
ON ALL SERVER
FOR DROP_DATABASE
AS
IF EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]',
'nvarchar(max)') = 'myDbName'
BEGIN
/*Some code here*/
END
Yes. Forget this idea, find one that is supported.
As in: no way. I drop your DB (as admin), you are dead as db. point.
THere is also no way to implement a trigger in an exe that does stuff when the exe is deleted.
精彩评论