SQL删除磁盘文件
以前实现备份文件管理,有一个删除功能,是使用asp.net来实现删除备份文件。这段时间改用在SQL Server存储过程去实现。您可以参考到这个存储过程完整代码。
代码
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[usp_DeleteFile]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[usp_DeleteFile]
GO
CREATE PROCEDURE [dbo].[usp_DeleteFile]
(
@FileName nvarchar(128)
)
AS
DECLARE @OutInfo TABLE
(
[FILE_EXISTS] INT NOT NULL,
[FILE_IS_DIRECTORY] INT NOT NULL,
[PARENT_DIRECTORY_EXISTS] INT NOT NULL
)
INSERT INTO @OutInfo EXECUTE [master].[dbo].xp_fileexist @FileName
DECLARE @Flag INT = (SELECT [FILE_EXISTS] FROM @OutInfo)
IF (@Flag = 1)
BEGIN
DECLARE @OrgBkFileString NVARCHAR(1000) = 'DEL "' + @FileName + '"'
EXECUTE master..xp_cmdshell @OrgBkFileString
END
IF @@ERROR <> 0
BEGIN
RAISERROR(N'Can not delete file.',16,1)
RETURN
END
DROP PROCEDURE [dbo].[usp_DeleteFile]
GO
CREATE PROCEDURE [dbo].[usp_DeleteFile]
(
@FileName nvarchar(128)
)
AS
DECLARE @OutInfo TABLE
(
[FILE_EXISTS] INT NOT NULL,
[FILE_IS_DIRECTORY] INT NOT NULL,
[PARENT_DIRECTORY_EXISTS] INT NOT NULL
)
INSERT INTO @OutInfo EXECUTE [master].[dbo].xp_fileexist @FileName
DECLARE @Flag INT = (SELECT [FILE_EXISTS] FROM @OutInfo)
IF (@Flag = 1)
BEGIN
DECLARE @OrgBkFileString NVARCHAR(1000) = 'DEL "' + @FileName + '"'
EXECUTE master..xp_cmdshell @OrgBkFileString
END
IF @@ERROR <> 0
BEGIN
RAISERROR(N'Can not delete file.',16,1)
RETURN
END