DECLARE @filename VARCHAR(500)
DECLARE @date DATETIME
DECLARE @OLD_DATE DATETIME
SET @date=GETDATE()
SET @OLD_DATE=GETDATE()-5 --超过5天的备份即将被删除
SET @FILENAME = 'E:\存放位置\数据库名称-'+CAST(DATEPART(YYYY,@DATE) AS VARCHAR(10))+'-'+CAST(DATEPART(MM,@DATE) AS VARCHAR(10))+'-'+CAST(DATEPART(DD,@DATE) AS VARCHAR(10))+'.BAK'
BACKUP DATABASE [数据库名称] TO DISK = @filename WITH COMPRESSION
EXECUTE master.dbo.xp_delete_file 0,N'E:\存放位置',N'bak',@OLD_DATE,1
GO
DECLARE @DBNAME VARCHAR(128)
DECLARE @PATH VARCHAR(50)
DECLARE @SQL NVARCHAR(MAX)
DECLARE @DDATE VARCHAR(8)
SET @PATH = 'E:\BackUp'
SET @DDATE = convert(char(8),getdate(),112)
--删除超过1天的备份
SET @SQL ='xp_cmdshell '' forfiles /p "'+@path+'" /d -0 /m *.bak /c "cmd /c echo deleting @file.... del /f @file"'''
EXEC (@SQL)
SET @SQL = ''
SELECT @SQL = @SQL + '
BACKUP DATABASE ['+NAME+'] TO DISK = '''+@PATH+'\'+REPLACE(name,'.','')+@DDATE+'.bak '''
FROM master..sysdatabases
WHERE NAME NOT IN ('master','tempdb','model','msdb')
EXEC (@SQL)
然后创建powershell脚本,将下边语句粘贴进去并保存成xx.ps1,在通过Windows的任务调度定时执行备份就可以了(我就是举个例子过期删除备份的语句也可以通过powershel实现,在家没有环境就随便写个思路没写全各位见谅)。