Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Enterprise
Expertise: Intermediate
Jul 27, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Delete Files from SQL Server Local Machine

Ever wanted to delete files from the local machine that your SQL Server database is running? You can do it using the extended stored procedure xp_cmdshell like this:
 EXEC master..xp_cmdshell 'del C:\file.txt'
But this requires the sysadmin option on the SQL Server and Admin role from NT server. In most instances it is not preferable to give these privileges. So to delete files without requiring this access use the built-in SQL Server Automation APIs and the FileSystemObject:
 DECLARE @hr 		int
DECLARE @ole_FileSystem		int

EXEC @hr = sp_OACreate 'Scripting.FileSystemObject', 
@ole_FileSystem OUT

EXEC @hr = sp_OAMethod @ole_FileSystem, 'DeleteFile', 
     		     NULL, 'C:\file.txt'

EXEC @hr = sp_OADestroy @ole_FileSystem
Andrew Holliday
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date