码迷,mamicode.com
首页 > 数据库 > 详细

sqlserver 删除备份文件只保留最新的

时间:2016-11-24 11:56:17      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:pat   truncate   bak   data   ace   mss   begin   select   shell   


CREATE TABLE #DBNAME(ID int identity(1,1),dbname nvarchar(100))
CREATE TABLE #BAK(ID int identity(1,1),bak nvarchar(120))
DECLARE @BakDir nvarchar(100) = ‘dir /b /a:d G:\sqldata\mssql\backup\‘
DECLARE @DelStr nvarchar(2000)

INSERT INTO #DBNAME
EXEC xp_cmdshell @BakDir

DELETE #DBNAME WHERE dbname IS NULL

DECLARE @count int
SELECT @count = COUNT(1) FROM #DBNAME

DECLARE @ID int = 1
DECLARE @DBName nvarchar(100)
DECLARE @path nvarchar(200)

WHILE @ID <= @count
BEGIN
SET @path = ‘‘
SET @DBName = NULL
TRUNCATE TABLE #BAK
SELECT @DBName = dbname FROM #DBNAME WHERE ID = @ID
IF @DBName IS NOT NULL
BEGIN
SET @path = ‘dir /b /o:-d G:\sqldata\mssql\backup\‘ + @DBName
DECLARE @CD nvarchar(100)=‘G:\sqldata\mssql\backup\‘ + @DBName +‘\‘
INSERT INTO #BAK
EXEC xp_cmdshell @path

DELETE #BAK WHERE bak IS NULL
SET @DelStr = ‘DEL ‘
IF (SELECT COUNT(1) FROM #BAK) > 1
BEGIN
SELECT @DelStr+= @CD+bak+‘ ‘ FROM #BAK WHERE ID <> 1
SET @DelStr = @DelStr+‘)‘
SELECT @DelStr = REPLACE(@DelStr,‘ )‘,‘‘)
PRINT @DelStr
EXEC xp_cmdshell @DelStr
END
END
SET @ID += 1
END

DROP TABLE #DBNAME
DROP TABLE #BAK

 

sqlserver 删除备份文件只保留最新的

标签:pat   truncate   bak   data   ace   mss   begin   select   shell   

原文地址:http://www.cnblogs.com/sandra/p/6096882.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!