如果数据库创建日期超过3个月,如何备份和删除SQL Server数据库

时间:2017-05-01 20:23:36

标签: sql-server tsql database-backups

如果数据库创建日期超过3个月,如何备份和删除SQL Server数据库

1 个答案:

答案 0 :(得分:0)

小心使用这样的东西,这个脚本可能会让你陷入困境。注意我只选择@tsql参数,我注释掉EXEC,这样你就可以看到首先要执行的内容。

/* Create a cursor to iterate through the databases you want to backup and delete */

DECLARE @tsql nvarchar(max)
DECLARE @dbname varchar(500)

DECLARE MyCursor CURSOR STATIC FORWARD_ONLY 
FOR
SELECT [name]
FROM sys.databases
WHERE create_date < DATEADD (M, -3, GETDATE())
AND [name] NOT IN ('master', 'model', 'msdb', 'tempdb')

OPEN MyCursor 

WHILE (1=1)   
BEGIN
DECLARE 
    @Date varchar(20) = GETDATE()

FETCH NEXT FROM MyCursor INTO @dbname  
IF @@FETCH_STATUS <> 0 BREAK 

SET @tsql = 'BACKUP DATABASE [' + @dbname + '] TO  DISK = N''S:\Backups\' + @dbname + ' ' + @Date + '.bak'' WITH NOFORMAT, NOINIT, SKIP, NOREWIND, NOUNLOAD, COMPRESSION,  STATS = 10'
SELECT @tsql;
-- EXEC sp_executesql @tsql 
SET @tsql = 'ALTER DATABASE [' + @dbname + '] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [' + @dbname + ']'
SELECT @tsql
-- EXEC sp_executesql @tsql 

END   
CLOSE MyCursor;   
DEALLOCATE MyCursor;    
GO