国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > 数据库 > Sqlserver > 一次性备份SQL Server中所有的数据

一次性备份SQL Server中所有的数据

来源:程序员人生   发布时间:2013-11-13 23:22:46 阅读次数:2736次
本文原始来自网上一篇文章,不过原始的存储过程有些问题,本文经过验证并进行了进一步的修正,增加了备份的时候自动增加备份日期,文章内容如下:

备份处理的存储过程

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

/*--备份所有数据库

备份的文件名为数据库名+日期+.bak
将所有的用户数据库(或指定的数据库列表)
备分到指定的目录下.

/*--调用示例

--备份所有用户数据库
exec p_backupdb @bkpath='D:',@dbname=''

--备份指定数据库
exec p_backupdb @bkpath=D:',@dbname='数据库名称'
--*/

create proc [dbo].[p_backupdb]
@bkpath nvarchar(260)='D:', --备份文件的存放目录,不指定则使用SQL默认的备份目录
@dbname nvarchar(4000)='' --要备份的数据库名称列表,不指定则备份所有用户数据库
as
declare @sql varchar(8000)
DECLARE @strdate NVARCHAR(200)
set @strdate = convert(NVARCHAR(10),getdate(),120)
set @strdate = REPLACE(@strdate, '-' , '')

--检查参数
if isnull(@bkpath,'')=''
begin
select @bkpath=rtrim(reverse(filename)) from master..sysfiles where name='master'
select @bkpath=substring(@bkpath,charindex('',@bkpath)+1,4000)
,@bkpath=reverse(substring(@bkpath,charindex('',@bkpath),4000))+'BACKUP'
end
else if right(@bkpath,1)<>'' set @bkpath=@bkpath+''

--得到要备份的数据库列表
if isnull(@dbname,'')=''
declare tb cursor local for
select name from master..sysdatabases where name not in('master','tempdb','model','msdb')
else
declare tb cursor local for
select name from master..sysdatabases
where name not in('master','tempdb','model','msdb') and(name like '%'+@dbname+'%')

--备份处理
open tb
fetch next from tb into @dbname
while @@fetch_status=0
begin
set @sql='backup database '+@dbname
+' to disk='''+@bkpath+@dbname +'_'+@strdate
+'.bak'' with format'
exec(@sql)
fetch next from tb into @dbname
end
close tb
deallocate tb
go
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生