CREATE proc [dbo].[usp_autoBackupDB]
@dbname sysname=null --要备份的数据库名,不指定即为全部备份,@path nvarchar(128)='d:\' --备份目录路径,@backup_type varchar(16)='database' --备份类型,可以为database,log,@backup_sysdb int=0 --是否备份系统数据库,0为不备份,1为备份asset nocount on;declare @dbcnt int =0
,@sql varchar(2000)='',@except_db varchar(1000)=case @backup_sysdb when 0 then ''''+'master'+''''+','+'''' +'msdb'+''''+','+''''+'tempdb'+''''+','+''''+'model'+''''when 1 then '' end;declare @db_list table(id int identity(1,1) not null,name sysname);declare @backup_err_list table(id int identity(1,1) not null,name sysname); if right(@path,1)<>'\'set @path=@path+'\'if @dbname is null or @dbname in ('all','*')
begin--将所有数据库名存到一张临时表上set @sql='select name from sys.databases where name not in ('+@except_db+');'insert into @db_list(name) exec(@sql);--得到一共有多少个数据库
select @dbcnt=count(1) from @db_list;--开始循环while @dbcnt>0begin--从临时表中获得最后一个数据库的名字select @dbname=name from @db_list where id=@dbcnt;set @sql='backup '+@backup_type+' '+@dbname+' to disk='+''''+@path+@backup_type+'_'+@dbname+'.'+convert(varchar(8),getdate(),112)+'.'+DATENAME(HH,GETDATE())+''''--开始循环备份exec (@sql);if @@ERROR<>0insert into @backup_err_list(name) values(@dbname);set @dbcnt=@dbcnt-1endendelsebeginset @sql='backup '+@backup_type+' '+@dbname+' to disk='+''''+@path+@backup_type+'_'+@dbname+'.'+convert(varchar(8),getdate(),112)+'.'+DATENAME(HH,GETDATE())+''''--仅备份一次exec (@sql);if @@ERROR<>0insert into @backup_err_list(name) values(@dbname);end
if exists(select * from @backup_err_list)select ID ,name as 'backup_err_dbname' from @backup_err_list;else print 'backup success';set nocount off;
GO