sardine254

        
posts - 12, comments - 3, trackbacks - 0, articles - 23
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

数据库备份

Posted on 2006-04-16 19:32 sardine 阅读(130) 评论(0) 编辑 收藏

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 init'
exec(@sql)
fetch next from tb into @dbname
end
close tb
deallocate tb
go