900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 通过SQL存储过程删除过期的数据库Bak备份文件

通过SQL存储过程删除过期的数据库Bak备份文件

时间:2023-05-22 03:47:57

相关推荐

通过SQL存储过程删除过期的数据库Bak备份文件

1.先启用 xp_cmdshell 扩展存储过程:

UseMaster

GO

Execsp_configure'showadvancedoptions',1

GO

Reconfigure;

GO

sp_configure'xp_cmdshell',1

GO

Reconfigure;

GO

(注:因为xp_cmdshell是高级选项,所以这里启动xp_cmdshell,需要先将 show advanced option 设置为 1,便可显示高级配置选项。

可以通过语句

Selectis_advancedFromsys.configurationsWherename=N'xp_cmdshell'

查看是否高级选项。

)

2.删除文件的存储过程:

Ifobject_id('sp_DeleteFiles')IsNotNull

DropProcsp_DeleteFiles

Go

CreateProcsp_DeleteFiles

(

@FilePathnvarchar(128),

@SearchPatternnvarchar(200),

@LastWriteTimeStartdatetime,

@LastWriteTImeEnddatetime

)

As

SetNocountOn

Declare@Cmdnvarchar(2000),

@OutputInfonvarchar(2000),

@Dirnvarchar(2000),

@Datedatetime,

@FileNamenvarchar(512)

Declare@TmpTable(IDintIdentity(1,1)PrimaryKey,OutputInfonvarchar(2000))

Set@Cmd=N'Dir/A:-d/S/T:W/4'+@FilePath+N'\'+Rtrim(@SearchPattern)/*Dos显示文件代码*/

InsertInto@Tmp

Execxp_cmdshell@Cmd

DeclareCur_dirCursorFor

SelectOutputInfoFrom@tmpWherePatindex('%\%',OutputInfo)>0OrIsDate(substring(OutputInfo,1,10))=1/*过滤只留目录和文件列表*/

OpenCur_dir

FetchNextFromCur_dirInto@OutputInfo

While@@Fetch_Status=0

Begin

IfPatindex('%\%',@OutputInfo)>0/*提取目录*/

Set@Dir=Substring(@OutputInfo,1,Len(@OutputInfo)-Charindex(Char(32),Reverse(@OutputInfo)))

Else

Begin

Set@Date=Substring(@OutputInfo,1,10)

If@DateBetween@LastWriteTimeStartAnd@LastWriteTImeEnd

Begin

/*不同的环境,如在繁体系统,这里取文件名的处理方法可能不同*/

Set@OutputInfo=Stuff(@OutputInfo,1,17,'')/*过滤掉日期部分*/

Set@OutputInfo=Stuff(@OutputInfo,1,Patindex('%[0-9]%',@OutputInfo)-1,'')/*过滤掉前缀的空格部分*/

Set@FileName=Stuff(@OutputInfo,1,Charindex(Char(32),@OutputInfo),'')/*取得文件名*/

Set@Cmd=N'Del'+@Dir+N'\'+@FileName

Execxp_cmdshell@Cmd,No_output

PrintN'已删除文件:'+@Dir+N'\'+@FileName

End

End

FetchNextFromCur_dirInto@OutputInfo

End

CloseCur_dir

DeallocateCur_dir

Go

3. 测试:

Execsp_DeleteFiles'F:\test','*.exe','20011001','1119'

/*

已删除文件:F:\test\Gao\高-8-14\B2000HR_FuXing_CHN_060406\HR_FuXing_071101.exe

已删除文件:F:\test\Gao\高-8-14\B2000HR_FuXing_CHN_060406\HR_FuXing_080127.exe

已删除文件:F:\test\Gao\高-8-14\B2000HR_FuXing_CHN_060406\HR_FuXing_080326.exe

已删除文件:F:\test\Gao\高-8-14\B2000HR_FuXing_CHN_060406\HR_FuXing_080328.exe

已删除文件:F:\test\Gao\高-8-14\B2000HR_FuXing_CHN_060406\HR_FuXing_080504.exe

已删除文件:F:\test\Gao\高-8-14\B2000HR_FuXing_CHN_060406\HR_FuXing_080628.exe

*/

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。