189.备份所有用户数据库

76 阅读1分钟
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
	将所有的用户数据库(或指定的数据库列表)
	备分到指定的目录下.

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

/*--调用示例

--备份所有用户数据库
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