Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete files on the directory via MS SQL Server

I am trying to delete a file from a directory inside windows using the following query,

exec xp_cmdshell 'del "C:\root\sfd_devtracker\'+@deletefile + '"';

When i execute this command it gives the following error,

Incorrect syntax near '+'.

In @deletefile variable i have the filename which i have to delete. What have i done wrong here?

like image 771
Nisal Malinda Livera Avatar asked Apr 07 '17 04:04

Nisal Malinda Livera


People also ask

How do I delete data from Microsoft SQL Server?

Using SQL Server Management StudioIn Object Explorer, connect to an instance of the SQL Server Database Engine, and then expand that instance. Expand Databases, right-click the database to delete, and then click Delete. Confirm the correct database is selected, and then click OK.

How do you delete multiple files in SQL?

There are a few ways to delete multiple rows in a table. If you wanted to delete a number of rows within a range, you can use the AND operator with the BETWEEN operator. DELETE FROM table_name WHERE column_name BETWEEN value 1 AND value 2; Another way to delete multiple rows is to use the IN operator.

Which command is used to remove files in SQL?

The DELETE command is used to delete existing records in a table.


1 Answers

declare @typeFile int = 0; -- for backup files or 1 for report files.
declare @folderPath varchar(max) = N'C:\temp'; --The folder to delete files.
declare @fileExtension varchar(100) = N'bak'; --File extension.
declare @cutOffDate datetime = DATEADD(hour , -12, getdate()); --The cut off date for what files need to be deleted.
declare @subFolder int = 0; --0 to ignore subFolders, 1 to delete files in subFolders.


EXECUTE master.dbo.xp_delete_file @typeFile, @folderPath, @fileExtension, @cutOffDate, @subFolder;

Credits: https://www.patrickkeisler.com/2012/11/how-to-use-xpdeletefile-to-purge-old.html

like image 65
Lucenio Marques Avatar answered Sep 28 '22 20:09

Lucenio Marques