首页 > 数据库 >SQLServer 批量备份与还原

SQLServer 批量备份与还原

时间:2023-04-30 10:32:55浏览次数:37  
标签:set 批量 int 备份 SQLServer numeric DatabBaseBakPath bit nvarchar


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

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

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

    脚本主要的功能:

 

   


批量备份数据库:

SQLServer 批量备份与还原_EXEC


-----------------------------批量备份数据-------------------------------------------

Use master
GO

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

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
  EXECUsp_BackUp_DataBase @dbname,@backup_path
  FETCH NEXT FROM db_info INTO @dbname
 END
close db_info
deallocate db_info



---------------------------------BackUp DataBase End------------------------------------

SQLServer 批量备份与还原_EXEC



检查还原磁盘:

SQLServer 批量备份与还原_EXEC



Use master
GO

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

SQLServer 批量备份与还原_EXEC



还原单个数据库:


SQLServer 批量备份与还原_EXEC



Use master
GO

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)<</SPAN>1 OR (SUBSTRING(@PhysicalName,1,@endpos-1)<>@LastPhysicalName)
if(len(@DirSQL)<</SPAN>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



SQLServer 批量备份与还原_EXEC



批量还原数据库:



SQLServer 批量备份与还原_EXEC



Use master
GO

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

标签:set,批量,int,备份,SQLServer,numeric,DatabBaseBakPath,bit,nvarchar
From: https://blog.51cto.com/u_548275/6237735

相关文章

  • 云LIS系统基于ASP.NET CORE 3.1 MVC + SQLserver + Redis技术实践
    云LIS   利用云LIS实现区域内各级医院门诊、住院等日常医疗业务和行政业务的全流程管理和医院的无纸化运营,规范就医流程,提升医疗质量,提供科学决策支持,增强患者的就医体验。云LIS是为区域医疗提供临床实验室信息服务的计算机应用程序,可协助区域内所有临床实验室相互协调并......
  • stm32cubeIde中使用shift+鼠标单击批量删除多行代码
    先从一个位置点击鼠标左键,然后拖动滚动条在需要开始或者结束的地方按着shift在点击鼠标左键,这样就可以批量删除了,对于几千行的代码来说,特别有用!什么?一个文件不会这么多行?呵呵。你再想想。......
  • c宏实现批量设置参数
    点击查看代码#defineFOO(name)(uint64_t)name,#defineEMPTY()#defineDEFER(id)idEMPTY()#defineFOR_EACH(macro,x,...)CAT(FOR_EACH_,ff(__VA_ARGS__))(macro,x,##__VA_ARGS__)#defineFOR_EACH_0(macro,x,...)macro(x)DEFER(FOR_EACH_I)()(macro,_......
  • unity 把本地图片批量添加到 物体的脚本上 Texture 类型
    privatevoidAwake(){stringfilePath=System.Environment.CurrentDirectory+"/专利/";if(Directory.Exists(filePath)){//判断这个路径是否存在DirectoryInfodirection=newDirectoryInfo(filePath);floders=directi......
  • openGauss之物理备份与恢复实践操作(openGauss课程openGauss3.0.0)
    一、opengauss的背景和行业现状 2022年,七大openGauss商业版发布,是基于openGauss3.0推出商业发行版目前海量数据库Vastbase表现最佳,一直是TOP1作者认为之所以海量数据库Vastbase目前无法被同行超越,和各家研发实力和技术背景有关 众所周知,opengauss起源于postgresql,在此基......
  • 数据库还原失败System.Data.SqlClient.SqlError: 无法执行 BACKUP LOG,因为当前没有数
    https://www.shuzhiduo.com/A/1O5EbK6yd7/高版本可以兼容低版本的数据库哎。所以低版本可以直接还原到高版本。过程中提示数据库还原失败System.Data.SqlClient.SqlError:无法执行BACKUPLOG,因为当前没有数据库备份,按照链接中的第二个方法解决了: 在还原的界面中,取消勾选还......
  • php批量更新
    /****批量更新*@paramstring$table表名*@paramarray$values更新字段(二维数组)*@paramstring$indexkey值(主键)*@paramarray$wherewhere条件[['user_sn','=',2010000760],['nick','=',&#......
  • ansible 第一次批量导入ssh-key
    适用环境:所有主机具有相同的用户名和密码实现方式:通过ansiblehosts文件读取主机列表通过expect自动应答脚本出处:githubkubeasz\tools#!/bin/bash#此脚本为批量部署服务器sshkey使用#set-x#checkargscountiftest$#-ne3;thenecho-e"\nUsag......
  • SQLSERVER 动态生成列、合计行
    /*test110'2023-04-26','2023-04-26','全部','901100569,901100570,901100571,901100572,901100573';*/ALTERPROCEDURE[dbo].[test110]@StartDatedatetime,@EndDatedatetime,@unameVARCHAR(50)='......
  • 快速上手Linux核心命令(九):文件备份与压缩
    目录tar打包备份gzip压缩或解压文件zip打包和压缩文件unzip解压zip文件scp远程文件复制rsync文件同步工具这期呢主要说一说Linux中文件备份与压缩命令,一共6个命令。这6个命令都是平常工作中非常非常常用的。tar打包备份1、简介tar可以将多个文件压缩打包、压缩。是......