如何通过 MS SQL 服务器删除目录中的文件

How to delete files on the directory via MS SQL Server

我正在尝试使用以下查询从 windows 中的目录中删除文件,

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

当我执行此命令时,出现以下错误,

Incorrect syntax near '+'.

@deletefile 变量中我有我必须删除的文件名。我在这里做错了什么?

xp_cmdshell 要求将文字字符串作为参数传递。您不能即时构建值。

试试这个:

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

考虑必须启用 xp_cmdshell,例如 this way

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;

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