本文介绍使用存储过程一次性备份SQL服务器上所有数据库到指定目录下,并且增加了备份的时候自动增加备份日期,代码如下:

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

posted on 2010-01-19 23:41  opper  阅读(412)  评论(0编辑  收藏  举报

青丝网

脱发治疗

www.faako.com