-3

How to Backup and delete SQL Server database if the database created date is more than 3 months

1

1 Answer 1

0

Be careful using something like this, this script could get you in to trouble. Notice I am only selecting the @tsql parameter, I commented out the EXEC so you can see what would be executing first.

/* 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   
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.