Reputation: 2297
Can we delete the physical file from server when I delete the corresponding entry from database?
i.e., C:\Test\Test.txt -> when deleting this record from database, i need to delete the corresponding Test.txt file from mentioned location. Is there a way, I m using SQL 2008.
Any help would be highly appreciable..
Thanks
Upvotes: 4
Views: 15682
Reputation: 37566
I didnt tested this but i think it should work.
Try writing a stored procedure which has the filename as a parameter and delete it using the:
exec master.dbo.xp_cmdshell 'del <Filename>'
then create a trigger for after delete on the table containing the Filenames which calls the stored procedure and provides the Filename from table deleted, or maby you can run directly the command exec master.dbo.xp_cmdshell 'del ' from the trigger.
The better way would be to save the files as an Object in the Database instead of the file path, and when deleting you just delete the file Object.
Upvotes: 1
Reputation: 21766
The ways are:
xp_cmdshell
proc (exec master..xp_cmdshell 'del C:\Test\Test.txt')Both ways are ugly
And once again - it is the worst practice. Server should not delete user files, or any files, is they are not integral part of its database.
Upvotes: 3
Reputation: 16726
You could use CREATE TRIGGER FOR DELETE
to create a trigger that runs when rows are deleted. The SQL statement that is run upon deletion can walk through the table deleted
to get the deleted rows. For each row it can exec xp_cmdshell
. xp_cmdshell is disabled by default, so you must enable it first using exec sp_configure
.
Upvotes: 1