Use master;
Go
CREATE PROCEDURE Bakdb (@f varchar (max))
As
Begin
DECLARE @file varchar (max)
Set @[email protected]
Declare auth_cur cursor for select name from sysdatabases where name is not in (' Master ', ' model ', ' msdb ', ' reportserver ', ' Repor Tservertempdb ', ' tempdb ')
Open auth_cur;
DECLARE @dbname varchar (max)
FETCH NEXT from Auth_cur to @dbname
while (@ @fetch_status =0)
Begin
DECLARE @db varchar (max), @sql varchar (max)
Set @db = ' [' [email protected]+ '] '
Set @sql = ' '
Set @sql + = ' DECLARE @filename VARCHAR (500); '
Set @sql + = ' DECLARE @date DATETIME; '
Set @sql + = ' DECLARE @OLD_DATE DATETIME; '
Set @sql + = ' Set @date =getdate (); '
Set @sql + = ' Set @OLD_DATE =getdate ()-5; '--a backup of more than 5 days is about to be deleted
Set @sql + = ' Set @FILENAME = ' ' [email protected]+ ' \ ' +replace (@db, '/', ' _ ') + '-' +cast (DATEPART (YYYY, @DATE) as VARCHAR (10 ) + "-" +cast (DATEPART (MM, @DATE) as varchar) + '-' +cast (DATEPART (DD, @DATE) as varchar (10)) + '. BAK '; '
Set @sql + = ' BACKUP DATABASE ' [email protected]+ ' to DISK = @filename with COMPRESSION; '
Set @sql + = ' EXECUTE master.dbo.xp_delete_file 0,n ' [email protected]+ ', N ' bak ', @OLD_DATE, 1; '
EXEC (@sql)
FETCH NEXT from Auth_cur to @dbname
End
Close auth_cur;
Deallocate auth_cur;
End
GO
Back up all databases