您的位置:首页 > 数据库

备份所有数据库代码

2008-12-26 11:48 274 查看
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_backupdb]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[p_backupdb]
GO

/*--备份所有数据库

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

--邹建 2003.10(引用请保留此信息)--*/

/*--调用示例

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

--备份指定数据库
exec p_backupdb @bkpath='c:/',@dbname='客户资料,xzkh_new'
--*/

create proc p_backupdb
@bkpath nvarchar(260)='',    --备份文件的存放目录,不指定则使用SQL默认的备份目录
@dbname nvarchar(4000)=''    --要备份的数据库名称列表,不指定则备份所有用户数据库
as
declare @sql varchar(8000)

--检查参数
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(@dbname like '%,'+name+',%' or @dbname like name+',%' or @dbname like '%,'+name)

--备份处理
open tb
fetch next from tb into @dbname
while @@fetch_status=0
begin
set @sql='backup database '+@dbname
+' to disk='''+@bkpath+@dbname
+'.bak'' with format'
exec(@sql)
fetch next from tb into @dbname
end
close tb
deallocate tb
go
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: