SQL备份数据库

create proc sp_backupdatabase
@bak_path nvarchar(4000)=‘‘ --备份路径;
,@baktype int = null --备份类型为全备,1为差异备,2为日志备份
,@type int = null --设置需要备份的库,0为全部库,1为系统库,2为全部用户库,3为指定库,4为排除指定库;
,@dbnames nvarchar(4000)=‘‘ --需要备份或排除的数据库,用,隔开,当@type=3或4时生效
,@overdueDay int = null --设置过期天数,默认天;
,@compression int =0 --是否采用sql2008的压缩备份,0为否,1为采用压缩
as
--sql server 2005/2008备份/删除过期备份T-sql 版本v1.0
/*
author:perfectaction
date :2009.04
desc :适用于sql2005/2008备份,自动生成库文件夹,可以自定义备份类型和备份库名等
可以自定义备份过期的天数
删除过期备份功能不会删除最后一次备份,哪怕已经过期
如果某库不再备份,那么也不会再删除之前过期的备份
如有错误请指正,谢谢.
*/

set nocount on
--开启xp_cmdshell支持
exec sp_configure ‘show advanced options‘, 1
reconfigure with override
exec sp_configure ‘xp_cmdshell‘, 1
reconfigure with override
exec sp_configure ‘show advanced options‘, 0
reconfigure with override
print char(13)+‘------------------------‘

--判断是否填写路径
if isnull(@bak_path,‘‘)=‘‘
begin
print(‘error:请指定备份路径‘)
return
end

--判断是否指定需要备份的库
if isnull(ltrim(@baktype),‘‘)=‘‘
begin
print(‘error:请指定备份类型aa:0为全备,1为差异备,2为日志备份‘)
return
end
else
begin
if @baktype not between 0 and 2
begin
print(‘error:指定备份类型只能为,1,2: 0为全备,1为差异备,2为日志备份‘)
return
end
end
--判断是否指定需要备份的库
if isnull(ltrim(@type),‘‘)=‘‘
begin
print(‘error:请指定需要备份的库,0为全部库,1为系统库,2为全部用户库,3为指定库,4为排除指定库‘)
return
end
else
begin
if @type not between 0 and 4
begin
print(‘error:请指定需要备份的库,0为全部库,1为系统库,2为全部用户库,3为指定库,4为排除指定库‘)
return
end
end

--判断指定库或排除库时,是否填写库名
if @type>2
if @dbnames=‘‘
begin
print(‘error:备份类型为‘+ltrim(@type)+‘时,需要指定@dbnames参数‘)
return
end

--判断指定指定过期时间
if isnull(ltrim(@overdueDay),‘‘)=‘‘
begin
print(‘error:必须指定备份过期时间,单位为天,0为永不过期‘)
return
end

--判断是否支持压缩
if @compression=1
if charindex(‘2008‘,@@version)=0 or charindex(‘Enterprise‘,@@version)=0
begin
print(‘error:压缩备份只支持sql2008企业版‘)
return
end

--判断是否存在该磁盘
declare @drives table(drive varchar(1),[size] varchar(20))
insert into @drives exec(‘master.dbo.xp_fixeddrives‘)
if not exists(select 1 from @drives where drive=left(@bak_path,1))
begin
print(‘error:不存在该磁盘:‘+left(@bak_path,1))
return
end

--格式化参数
select @bak_path=rtrim(ltrim(@bak_path)),@dbnames=rtrim(ltrim(@dbnames))
if right(isnull(@bak_path,‘‘),1)!=‘\‘ set @[email protected]_path+‘\‘
if isnull(@dbnames,‘‘)!=‘‘ set @dbnames = ‘,‘[email protected]+‘,‘
set @dbnames=replace(@dbnames,‘ ‘,‘‘)

--定义变量
declare @bak_sql nvarchar(max),@del_sql nvarchar(max),@i int,@maxid int
declare @dirtree_1 table (id int identity(1,1) primary key,subdirectory nvarchar(600),depth int,files int)
declare @dirtree_2 table (id int identity(1,1) primary key,subdirectory nvarchar(600),depth int,files int,
dbname varchar(300),baktime datetime,isLastbak int)
declare @createfolder nvarchar(max),@delbackupfile nvarchar(max),@delbak nvarchar(max)

--获取需要备份的库名--------------------start
declare @t table(id int identity(1,1) primary key,name nvarchar(max))
declare @sql nvarchar(max)
set @sql = ‘select name from sys.databases where state=0 and name!=‘‘tempdb‘‘ ‘
+ case when @baktype=2 then ‘ and recovery_model!=3 ‘ else ‘‘ end
+ case @type when 0 then ‘and 1=1‘
when 1 then ‘and database_id<=4‘
when 2 then ‘and database_id>4‘
when 3 then ‘and charindex(‘‘,‘‘+Name+‘‘,‘‘,‘‘‘[email protected]+‘‘‘)>0‘
when 4 then ‘and charindex(‘‘,‘‘+Name+‘‘,‘‘,‘‘‘[email protected]+‘‘‘)=0 and database_id>4‘
else ‘1>2‘ end
insert into @t exec(@sql)
--获取需要备份的库名---------------------end

--获取需要创建的文件夹------------------start
insert into @dirtree_1 exec(‘master.dbo.xp_dirtree ‘‘‘[email protected]_path+‘‘‘,0,1‘)
select @createfolder=isnull(@createfolder,‘‘)+‘exec master.dbo.xp_cmdshell ‘‘md ‘[email protected]_path+‘‘+name+‘‘‘,no_output ‘+char(13)
from @t as a left join @dirtree_1 as b on a.name=b.subdirectory and b.files=0 and depth=1 where b.id is null
--获取需要创建的文件夹-------------------end

--生成处理过期备份的sql语句-------------start
if @overdueDay>0
begin
insert into @dirtree_2(subdirectory,depth,files) exec(‘master.dbo.xp_dirtree ‘‘‘[email protected]_path+‘‘‘,0,1‘)
if @baktype =0
delete from @dirtree_2 where depth=1 or files=0 or charindex(‘_Full_bak_‘,subdirectory)=0
if @baktype =1
delete from @dirtree_2 where depth=1 or files=0 or charindex(‘_Diff_bak_‘,subdirectory)=0
if @baktype=2
delete from @dirtree_2 where depth=1 or files=0 or charindex(‘_Log_bak_‘,subdirectory)=0
if exists(select 1 from @dirtree_2)
delete from @dirtree_2 where isdate(
left(right(subdirectory,19),8)+‘ ‘+ substring(right(subdirectory,20),11,2) + ‘:‘ +
substring(right(subdirectory,20),13,2) +‘:‘+substring(right(subdirectory,20),15,2)
)=0
if exists(select 1 from @dirtree_2)
update @dirtree_2 set dbname = case when @baktype=0 then left(subdirectory,charindex(‘_Full_bak_‘,subdirectory)-1)
when @baktype=1 then left(subdirectory,charindex(‘_Diff_bak_‘,subdirectory)-1)
when @baktype=2 then left(subdirectory,charindex(‘_Log_bak_‘,subdirectory)-1)
else ‘‘ end
,baktime=left(right(subdirectory,19),8)+‘ ‘+ substring(right(subdirectory,20),11,2) + ‘:‘ +
substring(right(subdirectory,20),13,2) +‘:‘+substring(right(subdirectory,20),15,2)
from @dirtree_2 as a
delete @dirtree_2 from @dirtree_2 as a left join @t as b on b.name=a.dbname where b.id is null
update @dirtree_2 set isLastbak= case when (select max(baktime) from @dirtree_2 where dbname=a.dbname)=baktime
then 1 else 0 end from @dirtree_2 as a
select @delbak=isnull(@delbak,‘‘)+‘exec master.dbo.xp_cmdshell ‘‘del ‘[email protected]_path+‘‘+dbname+‘\‘
+subdirectory+‘‘‘,no_output ‘+char(13) from @dirtree_2 where isLastbak=0 and datediff(day,baktime,getdate())>@overdueDay
end
--生成处理过期备份的sql语句--------------end

begin try
print(@createfolder) --创建备份所需文件夹
exec(@createfolder) --创建备份所需文件夹
end try
begin catch
print ‘err:‘+ltrim(error_number())
print ‘err:‘+error_message()
return
end catch

select @i=1 ,@maxid=max(id) from @t
while @i<[email protected]
begin
select @bak_sql=‘‘+char(13)+‘backup ‘+ case when @baktype=2 then ‘log ‘ else ‘database ‘ end
+quotename(Name)+‘ to disk=‘‘‘[email protected]_path + Name+‘\‘+
Name+ case when @baktype=0 then ‘_Full_bak_‘ when @baktype=1 then ‘_Diff_bak_‘
when @baktype=2 then ‘_Log_bak_‘ else null end + case when @compression=1 then ‘compression_‘ else ‘‘ end+
replace(replace(replace(convert(varchar(20),getdate(),120),‘-‘,‘‘),‘ ‘,‘_‘),‘:‘,‘‘)+
case when @baktype=2 then ‘.trn‘ when @baktype=1 then ‘.dif‘ else ‘.bak‘ end +‘‘‘‘
+ case when @compression=1 or @baktype=1 then ‘ with ‘ else ‘‘ end
+ case when @compression=1 then ‘compression,‘ else ‘‘ end
+ case when @baktype=1 then ‘differential,‘ else ‘‘ end
+ case when @compression=1 or @baktype=1 then ‘ noformat‘ else ‘‘ end
from @t where [email protected]
set @[email protected]+1
begin try
print(@bak_sql)--循环执行备份
exec(@bak_sql) --循环执行备份
end try
begin catch
print ‘err:‘+ltrim(error_number())
print ‘err:‘+error_message()
end catch
end

begin try
print(@delbak) --删除超期的备份
exec(@delbak) --删除超期的备份
end try
begin catch
print ‘err:‘+ltrim(error_number())
print ‘err:‘+error_message()
end catch

--关闭xp_cmdshell支持
--exec sp_configure ‘show advanced options‘, 1
--reconfigure with override
--exec sp_configure ‘xp_cmdshell‘, 1
--reconfigure with override
--exec sp_configure ‘show advanced options‘, 0
--reconfigure with override

/*
调用示例:
--备份系统库(全备)
exec master.dbo.sp_backupdatabase
--备份路径;
@bak_path =‘D:\temp\dbbak‘
--备份类型为全备,1为差异备,2为日志备份
,@baktype = 0
--设置需要备份的库,0为全部库,1为系统库,2为全部用户库,3为指定库,4为排除指定库;
,@type = 1
--需要备份或排除的数据库,用,隔开,当@type=3或4时生效
,@dbnames =‘‘
--设置过期天数,默认天;
,@overdueDay = 31
--是否采用sql2008的压缩备份,0为否,1为采用压缩
,@compression =0

--备份用户库(全备)--建议一周一次
exec master.dbo.sp_backupdatabase
--备份路径;
@bak_path =‘D:\temp\dbbak‘
--备份类型为全备,1为差异备,2为日志备份
,@baktype = 0
--设置需要备份的库,0为全部库,1为系统库,2为全部用户库,3为指定库,4为排除指定库;
,@type = 3
--需要备份或排除的数据库,用,隔开,当@type=3或4时生效
,@dbnames =‘db1,db2‘
--设置过期天数,默认天;
,@overdueDay = 15
--是否采用sql2008的压缩备份,0为否,1为采用压缩
,@compression =0

--备份用户库(差异备)--建议一天一次
exec master.dbo.sp_backupdatabase
--备份路径;
@bak_path =‘D:\temp\dbbak‘
--备份类型为全备,1为差异备,2为日志备份
,@baktype = 1
--设置需要备份的库,0为全部库,1为系统库,2为全部用户库,3为指定库,4为排除指定库;
,@type = 3
--需要备份或排除的数据库,用,隔开,当@type=3或4时生效
,@dbnames =‘db1,db2‘
--设置过期天数,默认天;
,@overdueDay = 15
--是否采用sql2008的压缩备份,0为否,1为采用压缩
,@compression =0

--备份用户库(日志备)--建议1小时一次
exec master.dbo.sp_backupdatabase
--备份路径;
@bak_path =‘D:\temp\dbbak‘
--备份类型为全备,1为差异备,2为日志备份
,@baktype = 2
--设置需要备份的库,0为全部库,1为系统库,2为全部用户库,3为指定库,4为排除指定库;
,@type = 3
--需要备份或排除的数据库,用,隔开,当@type=3或4时生效
,@dbnames =‘db1,db2‘
--设置过期天数,默认天;
,@overdueDay = 15
--是否采用sql2008的压缩备份,0为否,1为采用压缩
,@compression =0
*/

时间: 2024-08-07 19:04:18

SQL备份数据库的相关文章

SQL备份数据库代码

#region 服务每天备份一次数据库 /// <summary> /// 服务每天备份一次数据库 /// </summary> public void ServiceForBackupDatabaseEveryDay() { Thread thread = new Thread(new ThreadStart(BackupDatabaseEveryDay)); thread.IsBackground = true; thread.Start(); } private void B

备份数据库

mysqldump  engine>/data/engine.2014.07.24.sql备份数据库,布布扣,bubuko.com

SQL Server 数据库定时自动备份【转】

在SQL Server中出于数据安全的考虑,所以需要定期的备份数据库.而备份数据库一般又是在凌晨时间基本没有数据库操作的时候进行,所以我们不可能要求管理员每天守到晚上1点去备份数据库.要实现数据库的定时自动备份,最常用的方式就是使用SQL Server代理中的作业.启动SQL Server Agent服务,然后在其中新建作业,作业中添加1个备份步骤,类型是T-SQL脚本,然后在命令中输入如下SQL语句,该语句实现了对数据库TestDB1的完整备份,备份文件在C盘Backup文件夹中,文件名就是T

sql server 2008 R2 压缩备份数据库

今天需要把一个省外项目的数据库从服务器上备份.拷贝到本机(跨地域传输数据库备份文件). 连上VPN,通过远程桌面连接,连接上服务器,发现数据库文件已经有20G以上大小了. 文件太大,公司网络也不稳定,根本不可能通过网络传输过来. 于是,把数据库的恢复模式由"完整"模式设置为"简单"模式,接着收缩数据库, 数据库瞬间由20G变成1G多点. 在SSMS中,新建查询窗口,执行数据库备份语句: --定义变量,把备份数据库的QL脚本赋值给变量 declare @SqlBack

Sql Server R2还有备份数据库错误

错误信息描述  该数据库是运行版本10.50.1600的服务器上备份的.该版本与此服务器(运行版本10.00.1600)不兼容.请在支持该被份的服务器上还原该数据,  或者使用与此服务器兼容的备份(MicrosoftSqlServer.Smo) 错误原因  本机上两个数据库一个是sql server版本,另个就sql server r2版本.  数据备份文件应该在sql server r2版本上附加而,我的sql server r2版本登陆所用的实例是sql server版本的所以引发数据还原不

SQL server数据库备份还原问题备忘(亲测有效)

问题一:SQL server数据库备份还原方法 http://www.cnblogs.com/zgqys1980/archive/2012/07/04/2576382.html 问题二:无法执行 BACKUP LOG,因为当前没有数据库备份 http://blog.csdn.net/aojiancc2/article/details/46316451 问题三:还原数据库失败 备份集中数据库备份与现有数据库不同 http://jingyan.baidu.com/article/fb48e8be52

SQL Server 数据库备份与还原

1.相同SQL Server版本(2008为例)之间数据库备份与还原 (1)数据库备份 相同SQL Server服务器版本之间数据库的备份还原操作相对来说比较简单. 首先找到需要备份的数据库实例,[右键]->[任务]->[备份...],界面下边选择备份路径,点击确定,备份成功后即可在选择的备份路径下找到后缀名为.bak的备份文件. (2)数据库还原 对于需要还原的.bak数据库文件,一般会先拷贝到 C:\Program Files\Microsoft SQL Server\MSSQL10.MS

SQL Server 数据库定时自动备份

原文:SQL Server 数据库定时自动备份 SQL Server 数据库定时自动备份——每天定时备份,保留前8天的备份 利用SQL Server代理新建作业来定期备份 1)在数据库库的[SQL Server代理]->[作业],右键[新建作业] 2)在[常规]选项卡设置[名称](自定义) 3)在[步骤]选项卡中点击[新建],然后在弹出的窗口的[常规]选项卡中设置“步骤名称”(自定义):选择“类型”为“Transact-SQL 脚本(T-SQL)”(默认):选择“数据库”为你要备份的数据库:添加

《SQL Server企业级平台管理实践》读书笔记——关于SQL Server数据库的备份方式

数据备份一直被认为数据库的生命,也就是一个DBA所要掌握的主要技能之一,本篇就是介绍SQL Server备份原则,SQL Server数据库分为数据文件和日志文件.为了使得数据库能够恢复一致点,备份不仅需要拷贝数据数据文件里的内容,还要拷贝日志文件里的内容.那么根据每次备份的目标不同,我们可以将备份分为数据备份和日志备份. 数据备份的范围可以是完整的数据库.部分数据库.一组文件或文件组.所以根据备份下来的数据文件的范围,又分为了完整数据库备份.文件备份和部分备份. 完整数据库备份 完整数据库备份