I use this script for getting backup from my sql server databases
DECLARE @name VARCHAR(50) -- database name
DECLARE @path VARCHAR(256) -- path for backup files
DECLARE @fileName VARCHAR(256) -- filename for backup
DECLARE @fileDate VARCHAR(20) -- used for file name
--Path to backups
SET @path = 'E:\DataBase Backups\'
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb','ReportServer','ReportServerTempDB')
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
--Remove if you dont want a date stamp
SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
-- SET @fileName = @path + @name + '.BAK'
BACKUP DATABASE @name TO DISK = @fileName with noinit
FETCH NEXT FROM db_cursor INTO @name
END
CLOSE db_cursor
DEALLOCATE db_cursor
This code makes new backup file per day, but I need to replace my old backup by today backup or after making today’s backup, all old backups became deleted!
Could you please help me?
You can use an undocumented extended stored procedure, xp_delete_file, to delete your backup files. Microsoft has internally added some safeguards to allow it to only delete database and transaction log backup files. So it can’t be used to delete any other file types; not even text files.
You need to declare a few extra variables.
Then add this code to your cursor loop.
@DeleteDate is what you use to tell the stored procedure which files to delete that are older than a certain date. Just use the DATEADD function to set the cutoff date.
@DeletePath will be your @path + @name so it will output something like ‘E:\DataBase Backups\MyDatabaseName’.
@FileExtention is used to tell what file types to delete; for example BAK’ or ‘TRN’.
I have been using this same code to purge old backup files in my custom TSQL backup jobs and it works great.