SQLServer 批量备份与还原

备份与还原是数据库避不开的主题,而作为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)     [email protected]+‘_‘     +convert(char(8),getdate(),112)+‘_‘    +replace(convert(char(8),getdate(),108),‘:‘,‘‘)     +‘.bak‘     set   @sql   =   ‘backup   database   ‘[email protected]   +   ‘   to   disk   =   N‘‘‘   +   @fn   +   ‘‘‘‘     --SELECT @sql   EXEC(@sql)    END

GO

Use 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>4

OPEN db_infoFETCH NEXT FROM db_info INTO @dbname

WHILE @@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                       [email protected]                       AND DSize>1024

               )      begin       set @errorinfo=N‘找不到还原磁盘:‘[email protected]+N‘ ,或者磁盘剩余空间小于1G‘       RAISERROR 50001 @errorinfo        set @ResultCount=0       return      end  endelse if(LEN(@RestoreDataPath)>1) AND CHARINDEX(‘:‘,@RestoreDataPath)=0  begin    set @errorinfo=N‘还原路径错误:‘[email protected]+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 on

declare @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 @[email protected]+‘\‘

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,0)        ,FileID bigint        ,CreateLSN numeric(25,0)        ,DropLSN numeric(25,0) NULL        ,UniqueID uniqueidentifier        ,ReadOnlyLSN numeric(25,0) NULL        ,ReadWriteLSN numeric(25,0) NULL        ,BackupSizeInBytes bigint        ,SourceBlockSize int        ,FileGroupID int        ,LogGroupGUID uniqueidentifier NULL        ,DifferentialBaseLSN numeric(25,0) NULL        ,DifferentialBaseGUID uniqueidentifier        ,IsReadOnly bit        ,IsPresent bit        ,TDEThumbprint varbinary(32)      )    

     INSERT INTO @BakFileList2008               EXEC sp_executesql N‘Restore FileListOnly From [email protected]‘,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,0)        ,FirstLSN numeric(25,0)        ,LastLSN numeric(25,0)        ,CheckpointLSN numeric(25,0)        ,DatabaseBackupLSN numeric(25,0)        ,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        ,IsReadOnly bit        ,IsSingleUser bit        ,HasBackupChecksums bit        ,IsDamaged bit        ,BeginsLogChain bit        ,HasIncompleteMetaData bit        ,IsForceOffline bit        ,IsCopyOnly bit        ,FirstRecoveryForkID uniqueidentifier        ,ForkPointLSN numeric(25,0) NULL        ,RecoveryModel nvarchar(60)        ,DifferentialBaseLSN numeric(25,0) NULL        ,DifferentialBaseGUID uniqueidentifier        ,BackupTypeDescription nvarchar(60)        ,BackupSetGUID uniqueidentifier NULL        ,CompressedBackupSize numeric(20,0)    )           

    INSERT INTO @BakHeaderInfo2008               EXEC sp_executesql N‘Restore HeaderOnly From [email protected]‘,N‘@DatabBaseBakPath nvarchar(260)‘,@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)        ,PhysicalName nvarchar(260)        ,Type char(1)        ,FileGroupName nvarchar(128)        ,SIZE numeric(20,0)        ,MaxSize numeric(20,0)        ,FileID bigint        ,CreateLSN numeric(25,0)        ,DropLSN numeric(25,0) NULL        ,UniqueID uniqueidentifier        ,ReadOnlyLSN numeric(25,0) NULL        ,ReadWriteLSN numeric(25,0) NULL        ,BackupSizeInBytes bigint        ,SourceBlockSize int        ,FileGroupID int        ,LogGroupGUID uniqueidentifier NULL        ,DifferentialBaseLSN numeric(25,0) NULL        ,DifferentialBaseGUID uniqueidentifier        ,IsReadOnly bit        ,IsPresent bit    )    

    INSERT INTO @BakFileList2005              EXEC sp_executesql N‘Restore FileListOnly From [email protected]‘,N‘@DatabBaseBakPath nvarchar(260)‘,@DatabBaseBakPath 

    DECLARE @BakHeaderInfo2005 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,0)        ,FirstLSN numeric(25,0)        ,LastLSN numeric(25,0)        ,CheckpointLSN numeric(25,0)        ,DatabaseBackupLSN numeric(25,0)        ,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        ,IsReadOnly bit        ,IsSingleUser bit        ,HasBackupChecksums bit        ,IsDamaged bit        ,BeginsLogChain bit        ,HasIncompleteMetaData bit        ,IsForceOffline bit        ,IsCopyOnly bit        ,FirstRecoveryForkID uniqueidentifier        ,ForkPointLSN numeric(25,0) NULL        ,RecoveryModel nvarchar(60)        ,DifferentialBaseLSN numeric(25,0) NULL        ,DifferentialBaseGUID uniqueidentifier        ,BackupTypeDescription nvarchar(60)        ,BackupSetGUID uniqueidentifier NULL    )    

    INSERT INTO @BakHeaderInfo2005                EXEC sp_executesql N‘Restore HeaderOnly From [email protected]‘,N‘@DatabBaseBakPath nvarchar(260)‘,@DatabBaseBakPath 

    insert into @BakHeaderInfo(DatabaseName)    select DatabaseName from @BakHeaderInfo2005

    insert into @BakFileList(LogicalName ,PhysicalName)    select  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‘取不到备份文件:‘[email protected]+N‘ 的信息,请检查备份文件是否正确或者版本是否兼容‘   Raiserror 50001 @errorinfo       Goto ExitFLag end

--Get DataBase NameSELECT TOP 1 @dbname=databasename FROM @BakHeaderInfo

if exists (select 1 from master.sys.databases with(nolock) where [email protected])     begin

       set @errorinfo=N‘数据库:‘[email protected]+N‘已经存在,不能还原‘        Raiserror 50001 @errorinfo         Goto ExitFLag     end

DECLARE @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 @BakFileList

OPEN db_file

set @DirSQL=‘‘set @SQL=+N‘RESTORE DATABASE ‘+QUOTENAME(@dbname)+‘ from disk=N‘‘‘[email protected]+‘‘‘‘set @[email protected]+char(13)+Char(10)+N‘ WITH FILE=1 ‘

FETCH NEXT FROM db_file INTO @LogicalName,@PhysicalName

WHILE @@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 @[email protected]+1;    end

   --create new db path   if(len(@RestoreDataPath)>1)      begin          set @[email protected][email protected]+‘\‘+SUBSTRING(@PhysicalName,@endpos,LEN(@PhysicalName)[email protected]+1)          set @DirSQL=N‘EXEC master.sys.xp_create_subdir N‘‘‘[email protected][email protected]+‘‘‘‘       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,1,@endpos-1)+‘‘‘‘          else           set @[email protected]+char(13)+N‘EXEC master.sys.xp_create_subdir N‘‘‘+SUBSTRING(@PhysicalName,1,@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,1,@endpos-1);      END

    set @[email protected]+char(13)+Char(10)+N‘ ,Move N‘‘‘[email protected]+‘‘‘‘+‘ TO N‘‘‘[email protected]+‘‘‘‘

   FETCH NEXT FROM db_file INTO @LogicalName,@PhysicalName end set @[email protected]+char(13)+Char(10)+N‘ ,NOUNLOAD,Recovery,STATS = 10‘

if(@IsRun=0)    print( @DirSQL+char(13)+char(10)+‘GO‘+char(13)+Char(10)[email protected]+char(13))else begin  print(‘-----------Begin Restore Database:‘[email protected]+‘------------------‘)  exec(@DirSQL)  exec(@SQL)  print(‘-----------End Restore Database:‘[email protected]+‘---------------------‘+char(13)) end

 close db_file deallocate db_file

ExitFLag: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 @[email protected]+‘\‘

--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                     ,1                     ,1

DELETE FROM @Dir WHERE charindex(‘.bak‘,BackDBFileName)=0

if not exists (select top 1 1 from @Dir)  begin   Raiserror 50001 N‘在提供的路径下没有找到合符要求的备份文件‘       Goto ExitFLag  end

declare db_file Cursor Local Static Read_Only Forward_Onlyforselect BackDBFileName from @Dir

Open db_fileFetch Next from db_file into @BackUpFileNamewhile @@FETCH_STATUS=0 begin  --Restore DataBase  set @[email protected][email protected]  exec master.dbo.Usp_RestoreDataBaseFormPath @BackUpFileName,@RestoreDataPath,@IsRun  Fetch Next from db_file into @BackUpFileName endClose db_filedeallocate db_file

ExitFLag:set nocount offend

时间: 2024-10-10 18:12:27

SQLServer 批量备份与还原的相关文章

关于 SQL Server 数据库批量备份与还原的一些 Tips

一.前提 最近需要将服务器 A 上的数据库全部备份,并在服务器 B 上进行还原,30多个数据库一个一个地用鼠标点,先是 backup,之后时 restore……整个过程实在是太浪费时间了!于是直接写一个小工具来批量备份还原数据库,这里记录一下一些 Tips,方便自己以后查看. 二.写配置文件 首先,我将数据库连接字符串和自动备份的目录路径写在了配置文件里,方便在以后数据库连接或者存储目录变动时,直接修改配置文件里的对应值就可以了. App.config 具体结构如下: <?xml version

Sqlserver事务备份和还原实例

1 create database mydb 2 use mydb 3 go 4 create table account( 5 id varchar(16), 6 name varchar(16), 7 balance float 8 ) 9 go 10 select * from account 11 12 insert into account(id, name, balance) values('620101', 'liyong', 300) 13 insert into account

sqlServer数据库备份与还原——差异备份与还原

1.差异备份 是完整备份的补充 备份自上次完整备份以来的数据变动的部分 2.备份过程: 在做差异备份之前需要先进行完整备份.完整备份的过程见:https://i.cnblogs.com/EditPosts.aspx?postid=10322955 差异备份与完整备份过程类似,只是备份类型选为差异备份 3.还原过程: 在进行差异还原的时候先要进行完整备份还原,但是要注意要选择上以下两个对勾,否则会报错. 不要着急点击确定,在选项中选中覆盖现有数据库,同时在恢复状态处选择第二个. 点击确定后,可以看

SQL Server 2008数据备份与还原的原理是什么?

为什么SqlServer有完整备份.差异备份和事务日志备份三种备份方式,以及为什么数据库又有简单模式.完整模式和大容量日志模式这三种恢复模式.本文内容适用于2005以上所有版本的SqlServer数据库. 单就操作过程而言,SqlServer中数据库备份和恢复过程是相当简单的,可以通过ManagementStudio的图形界面进行操作,也可以使用几句T-SQL语句完成.但要明白备份恢复的整个过程,定制符合系统需求数据库备份方案,却需要知晓数据库的实现原理.备份和恢复是数据库的核心功能. 可能许多

sqlserver日志的备份与还原

----------完整备份与还原----------                --完整备份数据库--backup database studb to disk='e:\stu.bak'backup log studb to disk='e:\stu_log.bak' use mastergo--还原数库库-- restore database studb from disk='e:\stu.bak' with replace,norecovery restore log studb fr

sqlserver多文件组数据库的备份和还原实战

数据库文件过大时就要进行数据分区,就是讲数据库拆分到多个文件组中.已方便数据文件管理,提高数据库的读取效能,多文件组如何进行数据库的备份和还原呢,今天主要做多文件组数据库的备份和还原实验. 第一步 创建数据库qhw_test 数据库包括一个userinfo 数据表,userinfo数据表根据id做分区 包括一个主分区 ,五个次分区,主分区包括qhw_test,data2两个文件, 数据表脚本如下 CREATE TABLE [dbo].[userinfo](    [Id] [int] IDENT

批量备份数据库脚本(PowerShell版)

开始 昨天备份一个数据库拿来测试,发现备份后的文件非常大.后来去检查下使用的备份脚本,原来之前的备份脚本没有压缩功能. 现把之前的备份脚本修改下,支持压缩备份,和支持仅复制备份(CopyOnly). 备份数据库(完整备份)脚本 (注:开初编写这脚本的目的是能批量备份数据库,提高工作效率,后面提到的还原数据库脚本也是如此.) <#=====================================================================#> ##备份数据库(完整备份

第三章 数据库备份和还原

一.数据库恢复模式 1.完整:能够让数据库恢复到出现故障的时间点和指定时间点(主要是日志文件完 整备份) 2.大容量日志:数据库日志不记录对数据修改的时间(即指定的时间点)效率高只 能通过日志恢复到故障点 3.简单:对事务日志不活跃的逻辑日志文件覆盖重复利用(日志写满后覆盖完成的 提交的事务日志)不能利用日志还原数据库,只能利用完整数据库文件恢 复 1)简单恢复模式 数据库备份和还原策略 数据小 数据变化不大 数据库不能恢复到出现故障的时间点(重复擦写日志文件) 完整数据库备份  完整的数据库备

数据库的复制与附加,备份与还原

数据库的复制与附加(一)分离:1.把SqlServer服务停了,把.mdf和.ldf,ndf复制出来.然后再启动服务.2.在SQLServer的操作界面中,右击要复制的数据库--所有任务--分离.把.mdf和.ldf,ndf复制出来.(二)附加在SQLServer对象资源管理器中,在“数据库”上右击--选择“附加”--在弹出的窗口选择要附加.mdf文件,点击确定.注意:两个文件.mdf和.ldf要有访问权限.Everyone完全控制. 数据库的备份与还原.(一)备份:在对象资源管理器中,右击要备