备份删除



CREATE TABLE #files
(
id INT IDENTITY(1, 1) ,
name VARCHAR(500)
)
DECLARE @dir VARCHAR(600)= 'E:\DataBaseBackup\'

DECLARE @dir1 VARCHAR(600)= 'dir ' + @dir

DECLARE @day INT= 8
--大于等于8天的备份

INSERT #files ( name )
EXEC xp_cmdshell @dir1;
WITH cte
AS ( SELECT name = @dir + RTRIM(LTRIM(REVERSE(LEFT(REVERSE(name),
CHARINDEX(' ',
REVERSE(name))))))
FROM #files
WHERE id > 5
AND name NOT LIKE '%DIR%'
AND name NOT LIKE '%字节%'
)
SELECT name
INTO #t1
FROM ( SELECT CASE WHEN id >= @day THEN '11'
ELSE NULL
END id, name
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY name DESC ) id,
*
FROM cte S0
WHERE S0.name LIKE '%SGPZ%'
UNION ALL
SELECT ROW_NUMBER() OVER ( ORDER BY name DESC ) id,
*
FROM cte S0
WHERE S0.name LIKE '%SCT%'
) s1
) s2
WHERE s2.id IS NOT NULL



DECLARE @ACTION1 VARCHAR(MAX)

DECLARE pcurr CURSOR
FOR
SELECT name
FROM #t1

OPEN pcurr
FETCH NEXT FROM pcurr INTO @ACTION1
WHILE ( @@FETCH_STATUS = 0 )
BEGIN

DECLARE @cmd VARCHAR(4000)= ''



SET @cmd = 'COPY ' + @ACTION1
+ CASE WHEN @ACTION1 LIKE '%SGPZ%'
THEN ' ' + REPLACE(@ACTION1, 'E:\DataBaseBackup\',
'd:\DataBaseBackup\SGPZ\')
ELSE ' ' + REPLACE(@ACTION1, 'E:\DataBaseBackup\',
'd:\DataBaseBackup\SCT\')
END
PRINT @cmd

EXEC xp_cmdshell @cmd --拷贝

SET @cmd = 'del ' + @ACTION1

PRINT @cmd

EXEC xp_cmdshell @cmd --删除

----------------------------
FETCH NEXT FROM pcurr INTO @ACTION1
END
CLOSE pcurr
DEALLOCATE pcurr




DROP TABLE #files
DROP TABLE #t1

posted @ 2012-10-31 11:38  qanholas  阅读(285)  评论(0编辑  收藏  举报