15

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?

Serge
  • 3,986
  • 2
  • 17
  • 37

2 Answers2

23

xp_cmdshell requires that a literal string be passed as parameter. You cannot construct a value on the fly.

Try this:

DECLARE @cmd NVARCHAR(MAX) = 
'xp_cmdshell ''del "C:\root\sfd_devtracker\' + @deletefile + '"''';
EXEC (@cmd)

Consider that xp_cmdshell must be enabled, for instance in this way.

bluish
  • 26,356
  • 27
  • 122
  • 180
Serge
  • 3,986
  • 2
  • 17
  • 37
4
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

  • Although you've given a possible solution here, you haven't actually answered the question. I think this answer could be improved by answering what is wrong with the OP's code, and why a different solution is necessary, better, etc. – guysherman Apr 30 '20 at 22:26
  • This is only useful for deleting database and log backup files, according the the blog post referenced. "Don’t let the stored procedure file name, xp_delete_file, fool you. Microsoft has some internal code that only allows for the deletion of database and transaction log backup files. The stored procedure cannot be used to delete any other type of file." – rocky May 18 '22 at 18:22