一次性備份SQL Server中所有的資料

iSQlServer發表於2010-01-13

本文原始來自網上一篇文章,不過原始的儲存過程有些問題,本文經過驗證並進行了進一步的修正,增加了備份的時候自動增加備份日期,文章內容如下:

備份處理的儲存過程   

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

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/16436858/viewspace-625025/,如需轉載,請註明出處,否則將追究法律責任。

相關文章