devxlogo

Delete Files from SQL Server Local Machine

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 fromNT 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 		intDECLARE @ole_FileSystem		intEXEC @hr = sp_OACreate 'Scripting.FileSystemObject', @ole_FileSystem OUTEXEC @hr = sp_OAMethod @ole_FileSystem, 'DeleteFile',      		     NULL, 'C:file.txt'EXEC @hr = sp_OADestroy @ole_FileSystem
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist