原文地址:http://www.cnblogs.com/fygh/archive/2011/09/09/2172546.html

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

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

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

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

脚本主要的功能:

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

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

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

说明:

脚本合适 SQLServer 2005 & 2008 版本;

 批量备份数据库:

-----------------------------批量备份数据-------------------------------------------
Use master
GO
/*=================Usp_BackUp_DataBase========================
=====BackUp Sigle DataBase ======
=====Ken.Guo ======
=====2010.9.10 ======
=====Version: 2005 & 2008 SQL Server ======
=====EXEC Usp_BackUp_DataBase 'MyDB','D:\BackUp' ======
============================================================
*/
CREATEPROC[dbo].[Usp_BackUp_DataBase]@DatabaseNamenvarchar(200),@Pathnvarchar(200)
AS
BEGIN
DECLARE@fnvarchar(200)
,@sqlvarchar(1000)
SET@fn=@Path+(casewhenright(@Path,1) <>'\'then'\'else''end)
+@DatabaseName+'_'
+convert(char(8),getdate(),112)+'_'
+replace(convert(char(8),getdate(),108),':','')
+'.bak'
set@sql='backup database '+@DatabaseName+' to disk = N'''+@fn+''''
--SELECT @sql
EXEC(@sql)
END GO Use master
GO
/*=============BackUp Mutile DataBase=========================*/
DECLARE@dbnamenvarchar(200)
,@backup_pathnvarchar(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_info
FETCHNEXTFROM db_info INTO@dbname WHILE@@FETCH_STATUS=0
begin
EXEC master.dbo.Usp_BackUp_DataBase @dbname,@backup_path
FETCHNEXTFROM db_info INTO@dbname
END
close db_info
deallocate db_info ---------------------------------BackUp DataBase End------------------------------------

检查还原磁盘:

Use master
GO
/*=================Check Restore Path Drives Exists==========================
=====Ken.Guo ======
=====2010.9.10 ======
=====EXEC Usp_Check_DriveExists @RestoreDataPath,@ResultCount OUTPUT ======
===========================================================================
*/
CREATEPROC Usp_Check_DriveExists(
@RestoreDataPathnvarchar(200)
,@ResultCountint OUTPUT)
AS
BEGIN
--Check Restore Path and Size >1000M
ifCHARINDEX(':',@RestoreDataPath)>0
begin
DECLARE@Drivenvarchar(10)
,@errorinfonvarchar(500) DECLARE@DriveListTABLE
(
Drive nvarchar(10)
,DSize bigint
)
INSERTINTO@DriveList
EXEC master.dbo.xp_fixeddrives SET@Drive=Left(@RestoreDataPath,CHARINDEX(':',@RestoreDataPath)-1)
ifnotexists(SELECT
*
FROM@DriveList
WHERE
Drive=@Drive
AND DSize>1024 )
begin
set@errorinfo=N'找不到还原磁盘:'+@Drive+N' ,或者磁盘剩余空间小于1G'
RAISERROR50001@errorinfo
set@ResultCount=0
return
end
end
elseif(LEN(@RestoreDataPath)>1) ANDCHARINDEX(':',@RestoreDataPath)=0
begin
set@errorinfo=N'还原路径错误:'+@RestoreDataPath+N',必须包含":" 号'
Raiserror50001@errorinfo
set@ResultCount=0
return
end
set@ResultCount=1
end
GO

还原单个数据库:

Use master
GO
/*=================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'
===================================================================================
*/
CREATEPROC Usp_RestoreDataBaseFormPath
(@DatabBaseBakPathnvarchar(400),
@RestoreDataPathnvarchar(400)='', --RESTORE DATABASE PATH
@IsRunsmallint=0-- 0 PRINT 1 run
)
AS
BEGIN
set nocount on declare@dbnamenvarchar(200),@SQLnvarchar(4000),@DirSQLnvarchar(1000),@errorinfonvarchar(300)
--add path \
if (@RestoreDataPathisnotnull) andlen(@RestoreDataPath)>1
and (right(@RestoreDataPath,1)<>'\')
set@RestoreDataPath=@RestoreDataPath+'\' declare@checkdriveint
set@checkdrive=1
exec master.dbo.Usp_Check_DriveExists @RestoreDataPath,@checkdrive output if(@checkdrive<>1)
Goto ExitFLag DECLARE@BakFileListTABLE
( LogicalName nvarchar(128)
,PhysicalName nvarchar(260)
) DECLARE@BakHeaderInfoTABLE
(
DatabaseName nvarchar(128)
) ifCharindex('Microsoft SQL Server 2008',@@VERSION)>0
begin
--SQL Server 2008
DECLARE@BakFileList2008TABLE
( 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 uniqueidentifierNULL
,DifferentialBaseLSN numeric(25,0) NULL
,DifferentialBaseGUID uniqueidentifier
,IsReadOnly bit
,IsPresent bit
,TDEThumbprint varbinary(32)
) INSERTINTO@BakFileList2008
EXEC sp_executesql N'Restore FileListOnly From Disk=@DatabBaseBakPath',N'@DatabBaseBakPath nvarchar(260)',@DatabBaseBakPath DECLARE@BakHeaderInfo2008TABLE
(
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 uniqueidentifierNULL
,CompressedBackupSize numeric(20,0)
) INSERTINTO@BakHeaderInfo2008
EXEC sp_executesql N'Restore HeaderOnly From Disk=@DatabBaseBakPath',N'@DatabBaseBakPath nvarchar(260)',@DatabBaseBakPath insertinto@BakHeaderInfo(DatabaseName)
select DatabaseName from@BakHeaderInfo2008 insertinto@BakFileList(LogicalName ,PhysicalName)
select LogicalName ,PhysicalName from@BakFileList2008
end
else
begin
--SQL Server 2005
DECLARE@BakFileList2005TABLE
(
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 uniqueidentifierNULL
,DifferentialBaseLSN numeric(25,0) NULL
,DifferentialBaseGUID uniqueidentifier
,IsReadOnly bit
,IsPresent bit
) INSERTINTO@BakFileList2005
EXEC sp_executesql N'Restore FileListOnly From Disk=@DatabBaseBakPath',N'@DatabBaseBakPath nvarchar(260)',@DatabBaseBakPath DECLARE@BakHeaderInfo2005TABLE
(
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 uniqueidentifierNULL
) INSERTINTO@BakHeaderInfo2005
EXEC sp_executesql N'Restore HeaderOnly From Disk=@DatabBaseBakPath',N'@DatabBaseBakPath nvarchar(260)',@DatabBaseBakPath insertinto@BakHeaderInfo(DatabaseName)
select DatabaseName from@BakHeaderInfo2005 insertinto@BakFileList(LogicalName ,PhysicalName)
select LogicalName ,PhysicalName from@BakFileList2005 end --Check back file info
ifnotexists (select1from@BakFileList) ORnotexists (select1from@BakHeaderInfo)
begin
set@errorinfo=N'取不到备份文件:'+@DatabBaseBakPath+N' 的信息,请检查备份文件是否正确或者版本是否兼容'
Raiserror50001@errorinfo
Goto ExitFLag
end --Get DataBase Name
SELECTTOP1@dbname=databasename FROM@BakHeaderInfo ifexists (select1from master.sys.databases with(nolock) where name=@dbname)
begin set@errorinfo=N'数据库:'+@dbname+N'已经存在,不能还原'
Raiserror50001@errorinfo
Goto ExitFLag
end DECLARE@LogicalNamenvarchar(200),@PhysicalNamenvarchar(400)
,@posint ,@endposint,@LastPhysicalNamenvarchar(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'''+@DatabBaseBakPath+''''
set@SQL=@SQL+char(13)+Char(10)+N' WITH FILE=1 ' FETCHNEXTFROM db_file INTO@LogicalName,@PhysicalName WHILE@@FETCH_STATUS=0
begin
---Get DB PhysicalName
set@endpos=0
whileCHARINDEX('\',@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
iflen(@DirSQL)<1OR (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@DirSQL=@DirSQL+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@SQL=@SQL+char(13)+Char(10)+N' ,Move N'''+@LogicalName+''''+' TO N'''+@PhysicalName+'''' FETCHNEXTFROM 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_file ExitFLag:
set nocount off
end

批量还原数据库:

Use master
GO
/*=================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 ======
=========================================================================
*/
CREATEPROC Usp_RestoreMuiteDataBaseFromPath
( @DatabBaseBakPathnvarchar(400)
,@RestoreDataPathnvarchar(400)=''--RESTORE DATABASE PATH
,@IsRunsmallint=0-- 0 PRINT 1 run
)
AS
BEGIN
set nocount on
DECLARE@BackUpFileNamenvarchar(200)
,@DbNamenvarchar(200)
,@errorinfonvarchar(400) IFnotexists(SELECT1
FROM master.sys.procedures WITH(NOLOCK)
WHERE
name=N'Usp_RestoreDataBaseFormPath' )
begin
Raiserror50001 N'找不到存储过程SP_RestoreDataBaseFormPath '
Goto ExitFLag
end --add path \
if (@DatabBaseBakPathisnotnull) andlen(@DatabBaseBakPath)>1
and (right(@DatabBaseBakPath,1)<>'\')
set@DatabBaseBakPath=@DatabBaseBakPath+'\' --Check Restore Path and Size >1000M
DECLARE@checkdriveint
SET@checkdrive=1
EXEC master.dbo.Usp_Check_DriveExists @RestoreDataPath,@checkdrive OUTPUT IF(@checkdrive<>1)
Goto ExitFLag DECLARE@DirTABLE
(
BackDBFileName nvarchar(100)
,DEPTH int
,[File]int
) INSERTINTO@DirEXEC xp_dirtree @DatabBaseBakPath
,1
,1 DELETEFROM@Dir
WHEREcharindex('.bak',BackDBFileName)=0 ifnotexists (selecttop11from@Dir)
begin
Raiserror50001 N'在提供的路径下没有找到合符要求的备份文件'
Goto ExitFLag
end declare db_file Cursor Local Static Read_Only Forward_Only
for
select BackDBFileName from@Dir Open db_file
FetchNextfrom db_file into@BackUpFileName
while@@FETCH_STATUS=0
begin
--Restore DataBase
set@BackUpFileName=@DatabBaseBakPath+@BackUpFileName
exec master.dbo.Usp_RestoreDataBaseFormPath @BackUpFileName,@RestoreDataPath,@IsRun
FetchNextfrom db_file into@BackUpFileName
end
Close db_file
deallocate db_file ExitFLag:
set nocount off
end

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

  1. SQLServer 批量备份与还原

    备份与还原是数据库避不开的主题,而作为DBA,经常会面临将一台机器上的所有数据库重新构建到一台新机器上的要求: 在现在都讲究自动化管理的时代,传统的界面操作备份还原的做法不仅浪费时间和精力,而且还很容 ...

  2. 批处理(bat)实现SQLServer数据库备份与还原

    原文:批处理(bat)实现SQLServer数据库备份与还原 备份数据库.bat @echo off set path=%path%;C:\Program Files (x86)\Microsoft ...

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

    一.前提 最近需要将服务器 A 上的数据库全部备份,并在服务器 B 上进行还原,30多个数据库一个一个地用鼠标点,先是 backup,之后时 restore……整个过程实在是太浪费时间了!于是直接写一 ...

  4. SqlServer批量备份多个数据库且删除3天前的备份

    /******************************************* * 批量备份数据库且删除3天前的备份 ************************************ ...

  5. Sqlserver事务备份和还原实例

    create database mydb use mydb go create table account( id ), name ), balance float ) go select * fro ...

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

    1.差异备份 是完整备份的补充 备份自上次完整备份以来的数据变动的部分 2.备份过程: 在做差异备份之前需要先进行完整备份.完整备份的过程见:https://i.cnblogs.com/EditPos ...

  7. sqlserver 2008备份与还原

    一.SQL数据库的备份: 1.依次打开 开始菜单 → 程序 → Microsoft SQL Server 2008 → SQL Server Management Studio → 数据库:Dside ...

  8. SqlServer 批量备份

    -- 实现方式1:使用游标 DECLARE @FileName VARCHAR(200), @CurrentTime VARCHAR(50), @DBName VARCHAR(100), @SQL V ...

  9. SqlServer数据库备份与还原

    http://v.youku.com/v_show/id_XMjA4NzcyNzUy.html http://v.youku.com/v_show/id_XMjA4Nzc0NDQw.html

随机推荐

  1. 发掘ListBox的潜力(一):自动调整横向滚动条宽度

    <自绘ListBox的两种效果>一文帖出之后,从反馈信息来看,大家对这种小技巧还是很认同.接下来我将继续围绕ListBox写一系列的文章,进一步发掘ListBox的潜力,其中包括:自动调整 ...

  2. 刚写好的读取多网卡IP地址的函数

    虽然现在一机多网卡已经很普遍(像Notebook带有线.无线.蓝芽等),但是找一个现成的能够一次过读出所有网卡IP地址的函数实在是难,无奈自己写了一个,好东西谁用谁知道. //uses WinSock ...

  3. 拍照图片滤镜sample

    本文章主要介绍拍完照片后对图片的渲染进行处理 可以对拍出的照片进行选择不同的滤镜,令在图片上附有编辑框,供大家对图片进行描述,这是一个可以手动拖动的编辑框,在这里主要介绍下,手指放到控件上什么情况下视 ...

  4. 怎样配置PHP环境和安装Zendstdio编辑器

    想学习PHP好久了.苦于环境配置不好,一直感觉无从下手. 在网上找了个视频: 李炎恢PHP教程 第一章前3节给出了具体的配置的方法,即安装Apache和Zendstudio 10.5仅仅须要照着视频做 ...

  5. POJ1273_Drainage Ditches(网络流)

    Drainage Ditches Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 54887   Accepted: 2091 ...

  6. 使用Curl进行抓取远程内容时url中文编码问题

    PHP中对于URL进行编码,可以使用 urlencode() 或者 rawurlencode(),二者的区别是前者把空格编码为 '+',而后者把空格编码为 '%20',不过应该注意的是,在编码时应该只 ...

  7. HDU 4296 Buildings (YY)

    题意: 给定N个物体,每个物体有两个参数w,s.   w代表它自身的重量: s代表它的强度.现在要把这些物体叠在一起,会产生一个PDV值. PDV解释:(Σwj)-si, where (Σwj) st ...

  8. eclipse如何查看类之间的引用关系

    今天遇到这个问题:mark一点点: 在类名上单击右键.选择Reference->Workingspace快捷克债券Ctrl+Shift+G 版权声明:本文博客原创文章,博客,未经同意,不得转载.

  9. 文档数据库RavenDB-介绍与初体验

    文档数据库RavenDB-介绍与初体验 阅读目录 1.RavenDB概述与特性 2.RavenDB安装 3.C#开发初体验 4.RavenDB资源 不知不觉,“.NET平台开源项目速览“系列文章已经1 ...

  10. 此三层非彼三层——MVC&amp;UBD

    学习了三年编程了,到如今这个阶段,開始接触架构,開始认识架构,怎样设计一个程序的结构,学名称"架构模式"(architectural pattern).个人经历告诉我这在编程中是一 ...