-----------------------------批量备份数据-------------------------------------------
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' ======
============================================================
*/
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),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 @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_info
FETCH 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
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 ======
===========================================================================
*/
CREATE PROC Usp_Check_DriveExists(
@RestoreDataPath nvarchar(200)
,@ResultCount int OUTPUT)
AS
BEGIN
--Check Restore Path and Size >1000M
if 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
end
else if(LEN(@RestoreDataPath)>1) AND CHARINDEX(':',@RestoreDataPath)=0
begin
set @errorinfo=N'还原路径错误:'+@RestoreDataPath+N',必须包含":" 号'
Raiserror 50001 @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'
===================================================================================
*/
CREATE PROC Usp_RestoreDataBaseFormPath
(@DatabBaseBakPath nvarchar(400),
@RestoreDataPath nvarchar(400)='', --RESTORE DATABASE PATH
@IsRun smallint=0 -- 0 PRINT 1 run
)
AS
BEGIN
set 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 @RestoreDataPath=@RestoreDataPath+'\' declare @checkdrive int
set @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 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,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 Disk=@DatabBaseBakPath',N'@DatabBaseBakPath nvarchar(260)',@DatabBaseBakPath insert into @BakHeaderInfo(DatabaseName)
select DatabaseName from @BakHeaderInfo2008 insert into @BakFileList(LogicalName ,PhysicalName)
select LogicalName ,PhysicalName from @BakFileList2008
end
else
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 Disk=@DatabBaseBakPath',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 Disk=@DatabBaseBakPath',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 info
if 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 Name
SELECT TOP 1 @dbname=databasename FROM @BakHeaderInfo if exists (select 1 from master.sys.databases with(nolock) where name=@dbname)
begin set @errorinfo=N'数据库:'+@dbname+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'''+@DatabBaseBakPath+''''
set @SQL=@SQL+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 @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,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+'''' 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_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 ======
=========================================================================
*/
CREATE PROC Usp_RestoreMuiteDataBaseFromPath
( @DatabBaseBakPath nvarchar(400)
,@RestoreDataPath nvarchar(400)='' --RESTORE DATABASE PATH
,@IsRun smallint=0 -- 0 PRINT 1 run
)
AS
BEGIN
set nocount on
DECLARE @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 >1000M
DECLARE @checkdrive int
SET @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_Only
for
select BackDBFileName from @Dir Open db_file
Fetch Next from db_file into @BackUpFileName
while @@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
end
Close db_file
deallocate db_file ExitFLag:
set nocount off
end

注:非原创,忘记该脚本原始出处

Backup--批量备份和还原的更多相关文章

  1. SQLServer批量备份与还原

    原文地址:http://www.cnblogs.com/fygh/archive/2011/09/09/2172546.html 备份与还原是数据库避不开的主题,而作为DBA,经常会面临将一台机器上的 ...

  2. SQLServer 批量备份与还原

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

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

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

  4. Database differential backup差异备份和还原

    完整备份: 备份全部选中的文件和文件夹,并不依赖文件的存档属性来确定备份哪些文件.(在备份过程中,任何现有的标记都被清除,每个文件都被标记为已备份,换言之,清除存档属性),完全备份也叫完整备份. 差异 ...

  5. Backup &recovery备份和还原

    实践版本:MySQL5.7 备份类型(backup type)物理和逻辑备份(Physical Versus Logical Backup)        物理备份是指直接复制存储数据库内容的目录和文 ...

  6. Backup&recovery备份和还原 mysql

    1.mysqldump 在日常工作中,我们会使用mysqldump命令创建sql格式的转储文件来备份数据库.或者我们把数据导出后做数据迁移,主备搭建等操作.mysqldump是一个逻辑备份工具,复制原 ...

  7. SQL Server2019数据库备份与还原脚本,数据库可批量备份

    前言 最近公司服务器到期,需要进行数据迁移,而数据库属于多而繁琐,通过图形化界面一个一个备份所需时间成本很大,所以想着写一个sql脚本来执行. 开始 数据库单个备份 数据库批量备份 数据库还原 数据库 ...

  8. 记一次 IIS 站点配置文件备份和还原,物理路径文件批量备份

    前言 上一篇文章实现了数据库的批量备份和还原,当然部署在服务器中的IIS站点备份也是一个十分繁琐的事,三四个数量不多的还好,像有一些服务器用了许久,承载几十个站点甚至更多,一个一个备份,再一个一个还原 ...

  9. MS SQL数据批量备份还原(适用于MS SQL 2005+) 分类: SQL Server 数据库 2015-03-10 14:32 103人阅读 评论(0) 收藏

    我们知道通过Sql代理,可以实现数据库的定时备份功能:当数据库里的数据库很多时,备份一个数据库需要建立对应的定时作业,相对来说比较麻烦: 还好,微软自带的osql工具,比较实用,通过在命令行里里输入命 ...

  10. MS SQL数据批量备份还原(适用于MS SQL 2005+)

    原文:MS SQL数据批量备份还原(适用于MS SQL 2005+) 我们知道通过Sql代理,可以实现数据库的定时备份功能:当数据库里的数据库很多时,备份一个数据库需要建立对应的定时作业,相对来说比较 ...

随机推荐

  1. 【转】javascript 执行环境,变量对象,作用域链

    这篇文章比较清晰的解释了一些作用域链相关的概念,忍不住收藏了 原文地址:http://segmentfault.com/a/1190000000533094 前言 这几天在看<javascrip ...

  2. Spring、Springboot常用注解:@Qualifier(不定时更新)

    1.@Qualifier 出现场景: 老项目中有多个实现类实现同一个接口时,或者一个项目中有多个数据源时,spring容器不知道该注入哪个实现类或者使用哪个数据源,该注解就派上用场. 1)多实现类实现 ...

  3. android学习-Eclipse中修改Android项目图标

    参考原文:http://blog.csdn.net/wpwbb510582246/article/details/52556753 方法一:替换res文件夹下的ic_launcher-web.png图 ...

  4. plsql中的光标

    操作oracle数据库效率最高的语言就是plsql程序,故而把访问数据库的代码写成plsql的执行效率要高于java,c ,c++等代码

  5. 全文搜索技术—Lucene

    1.   内容安排 实现一个文件的搜索功能,通过关键字搜索文件,凡是文件名或文件内容包括关键字的文件都需要找出来.还可以根据中文词语进程查询,并且支持多种条件查询. 本案例中的原始内容就是磁盘上的文件 ...

  6. vue的样式绑定

    vue在样式绑定,看这官方的文档,怎么试都不行后来看了一篇文章 <div :class="[rankClass]"></div> <script> ...

  7. 【祥哥带你玩HoloLens开发】了解如何实现远程主机为HoloLens实时渲染

    今天有一个兄弟在群里讲到他们的项目模型比较大,单用HoloLens运行设备的性能无法满足需要,问道如何将渲染工作交给服务器来做,讲渲染结果传给HoloLens.正好刚刚看官方github的时候发现一个 ...

  8. LIN通讯

    1.定义 LIN(Local Interconnect Network)总线是基于UART/SCI(通用异步收发器/串行接口)的低成本串行通讯协议.其目标定位于车身网络模块节点间的低端通信,主要用于智 ...

  9. activeMQ集群搭建及高可用

    三台服务器搭建如下的集群,达到了高可用.也同时达到了负载的目的: /****************************************************************** ...

  10. [C++] CONST 2

    The C++ 'const' Declaration: Why & How The 'const' system is one of the really messy features of ...