sqlserver2008数据库⾃动备份脚本
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为备份
as
set 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>0
begin
--从临时表中获得最后⼀个数据库的名字
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<>0
insert into @backup_err_list(name) values(@dbname);
set @dbcnt=@dbcnt-1
end
end
else
begin
set @sql='backup '+@backup_type+' '+@dbname+' to
disk='+''''+@path+@backup_type+'_'+@dbname+'.'+convert(varchar(8),getdate(),112)+'.'+DATENAME(HH,GETDATE())+'''' --仅备份⼀次
exec (@sql);
if @@ERROR<>0
insert 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';
sqlserver备份表语句set nocount off;
GO

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。