SQLServer 批量备份与还原

SQLServer 批量备份与还原,第1张

概述    备份还原是数据库避不开的主题,而作为DBA,经常会面临将一台机器上的所有数据库重新构建到一台新机器上的要求; 在现在都讲究自动化管理的时代,传统的界面 *** 作备份还原的做法不仅浪费时间和精力,而且还很容易出错,并且这次完成后, 下次再有这样的要求,必须又重头开始(估计做5次就能做得人狂吐);于是,我们需要一套应对这种频繁 *** 作、耗时、耗精力 的通用处理方法,所以以下批处理脚本就诞生了。    

    备份与还原是数据库避不开的主题,而作为DBA,经常会面临将一台机器上的所有数据库重新构建到一台新机器上的要求;

在现在都讲究自动化管理的时代,传统的界面 *** 作备份还原的做法不仅浪费时间和精力,而且还很容易出错,并且这次完成后,

下次再有这样的要求,必须又重头开始(估计做5次就能做得人狂吐);于是,我们需要一套应对这种频繁 *** 作、耗时、耗精力

的通用处理方法,所以以下批处理脚本就诞生了。

     脚本主要的功能:

     1. 备份一个服务器上的所有数据库(当然你也可以选择),备份文件按数据库名+日期生成,以.bak 结尾;

     2. 将所有的备份文件还原到一台新机器上;

     3. 验证磁盘和路径的正确性;

    说明:

     脚本合适 sqlServer 2005 & 2008 版本;

 

 批量备份数据库:

-----------------------------批量备份数据-------------------------------------------Use masterGO/*=================Usp_BackUp_DataBase========================  =====BackUp Sigle DataBase                            ======  =====Ken.Guo                                          ======  =====2010.9.10                                         ======  =====Version: 2005 & 2008 sql Server                  ======  =====EXEC Usp_BackUp_DataBase 'MyDB','D:\BackUp'      ======  ============================================================*/CREATE PROC   [dbo].[Usp_BackUp_DataBase] @Databasename   nvarchar(200),@Path   nvarchar(200)   AS    BEGIN   DECLARE   @fn   varchar(200),@sql   varchar(1000)     SET   @fn   =   @Path   +(case   when   right(@Path,1)   <>'\'   then   '\'   else   ''   end)     +@Databasename+'_'     +convert(char(8),getdate(),112)+'_'    +replace(convert(char(8),108),':','')     +'.bak'     set   @sql   =   'backup   database   '+@Databasename   +   '   to   disk   =   N'''   +   @fn   +   ''''     --SELECT @sql   EXEC(@sql)    ENDGOUse masterGO/*=============BackUp Mutile DataBase=========================*/DECLARE @dbname nvarchar(200),@backup_path nvarchar(200)SET @backup_path='D:\BackUp\'DECLARE db_info CURSOR     LOCAL     STATIC     READ_ONLY     FORWARD_ONLY FOR --根据查询,添加其他筛选条件  SELECT       name   FROM master.sys.databases WITH(NolOCK)   WHERE       database_ID>4OPEN db_infoFETCH NEXT FROM db_info INTO @dbnameWHILE @@FETCH_STATUS=0 begin  EXEC master.dbo.Usp_BackUp_DataBase @dbname,@backup_path  FETCH NEXT FROM db_info INTO @dbname ENDclose db_infodeallocate db_info---------------------------------BackUp DataBase End------------------------------------

检查还原磁盘:

Use masterGO/*=================Check Restore Path Drives Exists==========================  =====Ken.Guo                                                         ======  =====2010.9.10                                                        ======  =====EXEC Usp_Check_DriveExists @RestoreDataPath,@ResultCount OUTPUT ======  ===========================================================================*/CREATE PROC Usp_Check_DriveExists(      @RestoreDataPath nvarchar(200),@ResultCount int OUTPUT) ASBEGIN--Check Restore Path and Size >1000Mif CHARINDEX(':',@RestoreDataPath)>0  begin    DECLARE @Drive nvarchar(10),@errorinfo nvarchar(500)    DECLARE @DriveList table     (             Drive nvarchar(10),DSize bigint     )    INSERT INTO @DriveList     EXEC master.dbo.xp_fixeddrives    SET @Drive=left(@RestoreDataPath,CHARINDEX(':',@RestoreDataPath)-1)    if not exists(SELECT                       *                   FROM  @DriveList                   WHERE                       Drive=@Drive                       AND DSize>1024                              )      begin       set @errorinfo=N'找不到还原磁盘:'+@Drive+N' ,或者磁盘剩余空间小于1G'       RAISERROR 50001 @errorinfo        set @ResultCount=0       return      end  endelse if(LEN(@RestoreDataPath)>1) AND CHARINDEX(':',@RestoreDataPath)=0  begin    set @errorinfo=N'还原路径错误:'+@RestoreDataPath+N',必须包含":" 号'    Raiserror 50001 @errorinfo       set @ResultCount= 0    return   end set @ResultCount= 1endGO

还原单个数据库:

Use masterGO/*=================Usp_RestoreDataBaseFormPath=======================================  =====Restore Single DataBase From a Back file                                ======  =====Ken.Guo                                                                 ======  =====2010.9.10                                                                ======  =====Version: 2005 & 2008 sql Server                                         ======  =====Usp_RestoreDataBaseFormPath 'D:\databack\dbcenter.bak','D:\Data',0      ======  =====Key Point Info:                                                         ======  --Restore headerOnly  from disk='D:\data\xx.bak'  --Restore fileListOnly from disk='D:\data\xx.bak'  ===================================================================================*/CREATE PROC Usp_RestoreDataBaseFormPath(@DatabBaseBakPath nvarchar(400),@RestoreDataPath nvarchar(400)='',--RESTORE DATABASE PATH  @IsRun smallint=0 -- 0 PRINT  1 run ) ASBEGINset nocount ondeclare @dbname nvarchar(200),@sql nvarchar(4000),@Dirsql nvarchar(1000),@errorinfo nvarchar(300)--add path \if (@RestoreDataPath is not null) and len(@RestoreDataPath)>1    and (right(@RestoreDataPath,1)<>'\')   set @RestoreDataPath=@RestoreDataPath+'\'declare @checkdrive intset @checkdrive=1 exec master.dbo.Usp_Check_DriveExists @RestoreDataPath,@checkdrive output if(@checkdrive<>1)    Goto ExitFLag DECLARE @BakfileList table     (    Logicalname nvarchar(128),Physicalname nvarchar(260)    )DECLARE @BakheaderInfo table    (        Databasename nvarchar(128)    )if Charindex('Microsoft sql Server 2008',@@VERSION)>0  begin    --sql Server 2008        DECLARE @BakfileList2008 table     (    Logicalname nvarchar(128),Physicalname nvarchar(260),Type char(1),fileGroupname nvarchar(128),SIZE numeric(20,0),MaxSize numeric(20,fileID bigint,CreateLSN numeric(25,DropLSN numeric(25,0) NulL,UniqueID uniqueIDentifIEr,ReadonlyLSN numeric(25,ReaDWriteLSN numeric(25,BackupSizeInBytes bigint,SourceBlockSize int,fileGroupID int,LogGroupGUID uniqueIDentifIEr NulL,DifferentialBaseLSN numeric(25,DifferentialBaseGUID uniqueIDentifIEr,IsReadonly bit,IsPresent bit,TDEThumbprint varbinary(32)      )             INSERT INTO @BakfileList2008               EXEC sp_executesql N'Restore fileListOnly From disk=@DatabBaseBakPath',N'@DatabBaseBakPath nvarchar(260)',@DatabBaseBakPath     DECLARE @BakheaderInfo2008 table    (         Backupname nvarchar(128),BackupDescription nvarchar(255),BackupType smallint,ExpirationDate datetime,Compressed tinyint,position smallint,DeviceType tinyint,Username nvarchar(128),Servername nvarchar(128),Databasename nvarchar(128),DatabaseVersion int,DatabaseCreationDate datetime,BackupSize numeric(20,FirstLSN numeric(25,LastLSN numeric(25,CheckpointLSN numeric(25,DatabaseBackupLSN numeric(25,BackupStartDate datetime,BackupFinishDate datetime,SortOrder smallint,codepage smallint,UnicodeLocaleID int,UnicodeComparisonStyle int,CompatibilityLevel tinyint,SoftwarevendorID int,SoftwareversionMajor int,SoftwareversionMinor int,SoftwareversionBuild int,Machinename nvarchar(128),Flags int,BindingID uniqueIDentifIEr,RecoveryForkID uniqueIDentifIEr,ColLATION nvarchar(128),FamilyGUID uniqueIDentifIEr,HasBulkLoggedData bit,IsSnapshot bit,IsSingleUser bit,HasBackupChecksums bit,Isdamaged bit,BeginsLogChain bit,HasIncompleteMetaData bit,IsForceOffline bit,IscopyOnly bit,FirstRecoveryForkID uniqueIDentifIEr,ForkPointLSN numeric(25,RecoveryModel nvarchar(60),BackupTypeDescription nvarchar(60),BackupSetGUID uniqueIDentifIEr NulL,CompressedBackupSize numeric(20,0)    )               INSERT INTO @BakheaderInfo2008               EXEC sp_executesql N'Restore headerOnly From disk=@DatabBaseBakPath',@DatabBaseBakPath         insert into @BakheaderInfo(Databasename)    select Databasename from @BakheaderInfo2008    insert into @BakfileList(Logicalname,Physicalname)    select  Logicalname,Physicalname from @BakfileList2008  endelse  begin    --sql Server 2005        DECLARE @BakfileList2005 table     (         Logicalname nvarchar(128),IsPresent bit    )        INSERT INTO @BakfileList2005              EXEC sp_executesql N'Restore fileListOnly From disk=@DatabBaseBakPath',@DatabBaseBakPath       DECLARE @BakheaderInfo2005 table     (         Backupname nvarchar(128),BackupSetGUID uniqueIDentifIEr NulL    )        INSERT INTO @BakheaderInfo2005                EXEC sp_executesql N'Restore headerOnly From disk=@DatabBaseBakPath',@DatabBaseBakPath     insert into @BakheaderInfo(Databasename)    select Databasename from @BakheaderInfo2005    insert into @BakfileList(Logicalname,Physicalname from @BakfileList2005  end--Check back file infoif not exists (select 1 from @BakfileList) OR not exists (select 1 from @BakheaderInfo) begin   set @errorinfo=N'取不到备份文件:'+@DatabBaseBakPath+N' 的信息,请检查备份文件是否正确或者版本是否兼容'   Raiserror 50001 @errorinfo       Goto ExitFLag end--Get DataBase nameSELECT top 1 @dbname=databasename FROM @BakheaderInfoif exists (select 1 from master.sys.databases with(nolock) where name=@dbname)     begin              set @errorinfo=N'数据库:'+@dbname+N'已经存在,不能还原'        Raiserror 50001 @errorinfo         Goto ExitFLag     endDECLARE @Logicalname nvarchar(200),@Physicalname nvarchar(400),@pos int,@endpos int,@LastPhysicalname nvarchar(400)DECLARE db_file CURSOR     LOCAL     READ_ONLY     FORWARD_ONLY     STATIC FOR SELECT      Logicalname,Physicalname   FROM @BakfileListOPEN db_fileset @Dirsql=''set @sql=+N'RESTORE DATABASE '+QUOTEname(@dbname)+' from disk=N'''+@DatabBaseBakPath+''''set @sql=@sql+char(13)+Char(10)+N' WITH file=1 'FETCH NEXT FROM db_file INTO @Logicalname,@PhysicalnameWHILE @@FETCH_STATUS=0 begin   ---Get DB Physicalname   set @endpos=0   while CHARINDEX('\',@Physicalname)>0    begin      set @pos=CHARINDEX('\',@Physicalname,@endpos)      if(@pos=0)          break;      set @endpos=@pos+1;    end      --create new db path   if(len(@RestoreDataPath)>1)      begin          set @Physicalname=@RestoreDataPath+@dbname+'\'+SUBSTRING(@Physicalname,@endpos,LEN(@Physicalname)-@endpos+1)          set @Dirsql=N'EXEC master.sys.xp_create_subdir N'''+@RestoreDataPath+@dbname+''''       END    else      begin        if len(@Dirsql)<1 OR (SUBSTRING(@Physicalname,1,@endpos-1)<>@LastPhysicalname)          if(len(@Dirsql)<1)             set @Dirsql=N'EXEC master.sys.xp_create_subdir N'''+SUBSTRING(@Physicalname,@endpos-1)+''''          else           set @Dirsql=@Dirsql+char(13)+N'EXEC master.sys.xp_create_subdir N'''+SUBSTRING(@Physicalname,@endpos-1)+''''                ---Check Drives         set @checkdrive=1         exec master.dbo.Usp_Check_DriveExists @Physicalname,@checkdrive output         if(@checkdrive<>1)            Goto ExitFLag         set @LastPhysicalname=SUBSTRING(@Physicalname,@endpos-1);      END        set @sql=@sql+char(13)+Char(10)+N',Move N'''+@Logicalname+''''+' TO N'''+@Physicalname+''''       FETCH NEXT FROM db_file INTO @Logicalname,@Physicalname end set @sql=@sql+char(13)+Char(10)+N',NOUNLOAD,Recovery,STATS = 10'if(@IsRun=0)    print( @Dirsql+char(13)+char(10)+'GO'+char(13)+Char(10)+@sql+char(13))else begin  print('-----------Begin Restore Database:'+@dbname+'------------------')  exec(@Dirsql)  exec(@sql)  print('-----------End Restore Database:'+@dbname+'---------------------'+char(13)) end close db_file deallocate db_fileExitFLag:set nocount offend

批量还原数据库:

Use masterGO/*=================Usp_RestoreMuiteDataBaseFromPath========================  =====Restore Mutite DataBase file From a Path                      ======  =====Ken.Guo                                                       ======  =====2010.9.10                                                      ======  =====Version: 2005 & 2008 sql Server                               ======  =====EXEC Usp_RestoreMuiteDataBaseFromPath 'D:\databack','',0      ======  =========================================================================*/CREATE PROC Usp_RestoreMuiteDataBaseFromPath( @DatabBaseBakPath nvarchar(400),@RestoreDataPath nvarchar(400)=''  --RESTORE DATABASE PATH ,@IsRun smallint=0                   -- 0 PRINT 1 run ) ASBEGINset nocount onDECLARE @BackUpfilename nvarchar(200),@Dbname nvarchar(200),@errorinfo nvarchar(400)IF not exists(SELECT 1               FROM master.sys.procedures WITH(NolOCK)               WHERE                   name=N'Usp_RestoreDataBaseFormPath'                        )  begin   Raiserror 50001 N'找不到存储过程SP_RestoreDataBaseFormPath '       Goto ExitFLag  end--add path \if (@DatabBaseBakPath is not null) and len(@DatabBaseBakPath)>1    and (right(@DatabBaseBakPath,1)<>'\') set @DatabBaseBakPath=@DatabBaseBakPath+'\'--Check Restore Path and Size >1000MDECLARE @checkdrive intSET @checkdrive=1 EXEC master.dbo.Usp_Check_DriveExists @RestoreDataPath,@checkdrive OUTPUT IF(@checkdrive<>1)    Goto ExitFLag     DECLARE @Dir table (      BackDBfilename nvarchar(100),DEPTH int,[file] int )INSERT INTO @Dir EXEC xp_dirtree @DatabBaseBakPath,1DELETE FROM @Dir WHERE charindex('.bak',BackDBfilename)=0if not exists (select top 1 1 from @Dir)  begin   Raiserror 50001 N'在提供的路径下没有找到合符要求的备份文件'       Goto ExitFLag  enddeclare db_file Cursor Local Static Read_Only Forward_Onlyforselect BackDBfilename from @DirOpen db_fileFetch Next from db_file into @BackUpfilenamewhile @@FETCH_STATUS=0 begin  --Restore DataBase  set @BackUpfilename=@DatabBaseBakPath+@BackUpfilename  exec master.dbo.Usp_RestoreDataBaseFormPath @BackUpfilename,@RestoreDataPath,@IsRun  Fetch Next from db_file into @BackUpfilename endClose db_filedeallocate db_fileExitFLag:set nocount offend转自:  http://www.cnblogs.com/fygh/archive/2011/09/09/2172546.HTML
总结

以上是内存溢出为你收集整理的SQLServer 批量备份与还原全部内容,希望文章能够帮你解决SQLServer 批量备份与还原所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/1180450.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-02
下一篇 2022-06-02

发表评论

登录后才能评论

评论列表(0条)

保存