SQL SERVER 數據庫自動備份,恢復數據庫腳本

一、創建作業腳本 存儲過程 (在數據庫端執行即可) 


GO
/****** Object:  StoredProcedure [dbo].[sp_backupdatabase]    Script Date: 10/22/2019 20:45:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE proc [dbo].[sp_backupdatabase]
 @bak_path nvarchar(4000)=''       --備份路徑;
,@baktype int = null               --備份類型0爲全備,1爲差異備,2爲日誌備份
,@type int = null                  --設置需要備份的庫,0爲全部庫,1爲系統庫,2爲全部用戶庫,3爲指定庫,4爲排除指定庫;
,@dbnames nvarchar(4000)=''        --需要備份或排除的數據庫,用,隔開,當@type=3或4時生效
,@overdueDay int = null            --設置過期天數,默認天;
,@compression int =0               --是否採用sql2008的壓縮備份,0爲否,1爲採用壓縮
as
--sql server 2005/2008備份/刪除過期備份T-sql 版本v1.0
/*desc  :適用於sql2005/2008備份,自動生成庫文件夾,可以自定義備份類型和備份庫名等
      可以自定義備份過期的天數,刪除過期備份功能不會刪除最後一次備份,哪怕已經過期
       ,如果某庫不再備份,那麼也不會再刪除之前過期的備份 
*/
set nocount on
--開啓xp_cmdshell支持
exec sp_configure 'show advanced options', 1
reconfigure with override
exec sp_configure 'xp_cmdshell', 1 
reconfigure with override
exec sp_configure 'show advanced options', 0
reconfigure with override
print char(13)+'------------------------'
 
--判斷是否填寫路徑
if isnull(@bak_path,'')=''
    begin
        print('error:請指定備份路徑')
        return 
    end
 
--判斷是否指定需要備份的庫
if isnull(ltrim(@baktype),'')=''
    begin
        print('error:請指定備份類型aa:0爲全備,1爲差異備,2爲日誌備份')
        return 
    end
else
    begin
        if @baktype not between 0 and 2
        begin
            print('error:指定備份類型只能爲,1,2:  0爲全備,1爲差異備,2爲日誌備份')
            return 
        end
    end
--判斷是否指定需要備份的庫
if isnull(ltrim(@type),'')=''
    begin
        print('error:請指定需要備份的庫,0爲全部庫,1爲系統庫,2爲全部用戶庫,3爲指定庫,4爲排除指定庫')
        return 
    end
else
    begin
        if @type not between 0 and 4
        begin
            print('error:請指定需要備份的庫,0爲全部庫,1爲系統庫,2爲全部用戶庫,3爲指定庫,4爲排除指定庫')
            return 
        end
    end
 
--判斷指定庫或排除庫時,是否填寫庫名
if @type>2
    if @dbnames=''
    begin
        print('error:備份類型爲'+ltrim(@type)+'時,需要指定@dbnames參數')
        return 
    end
 
--判斷指定指定過期時間
if isnull(ltrim(@overdueDay),'')=''
begin
    print('error:必須指定備份過期時間,單位爲天,0爲永不過期')
    return 
end
 
--判斷是否支持壓縮
if @compression=1 
    if charindex('2008',@@version)=0 or charindex('Enterprise',@@version)=0
    begin
        print('error:壓縮備份只支持sql2008企業版')
        return 
    end
 
--判斷是否存在該磁盤
declare @drives table(drive varchar(1),[size] varchar(20))
insert into @drives exec('master.dbo.xp_fixeddrives')
if not exists(select 1 from @drives where drive=left(@bak_path,1))
    begin
        print('error:不存在該磁盤:'+left(@bak_path,1))
        return 
    end
 
--格式化參數
select @bak_path=rtrim(ltrim(@bak_path)),@dbnames=rtrim(ltrim(@dbnames))
if right(isnull(@bak_path,''),1)!='\' set @bak_path=@bak_path+'\'
if isnull(@dbnames,'')!='' set @dbnames = ','+@dbnames+','
set @dbnames=replace(@dbnames,' ','')
 
--定義變量
declare @bak_sql nvarchar(max),@del_sql nvarchar(max),@i int,@maxid int
declare @dirtree_1 table (id int identity(1,1) primary key,subdirectory nvarchar(600),depth int,files int)
declare @dirtree_2 table (id int identity(1,1) primary key,subdirectory nvarchar(600),depth int,files int,
dbname varchar(300),baktime datetime,isLastbak int)
declare @createfolder nvarchar(max),@delbackupfile nvarchar(max),@delbak nvarchar(max)
 
--獲取需要備份的庫名--------------------start
declare @t table(id int identity(1,1) primary key,name nvarchar(max))
declare @sql nvarchar(max)
set @sql = 'select name from sys.databases where state=0 and name!=''tempdb''  '
    + case when @baktype=2 then ' and recovery_model!=3 ' else '' end
    + case @type when 0 then 'and 1=1'
        when 1 then 'and database_id<=4'
        when 2 then 'and database_id>4'
        when 3 then 'and charindex('',''+Name+'','','''+@dbnames+''')>0'
        when 4 then 'and charindex('',''+Name+'','','''+@dbnames+''')=0 and database_id>4'
        else '1>2' end
insert into @t exec(@sql)
--獲取需要備份的庫名---------------------end
 
--獲取需要創建的文件夾------------------start
insert into @dirtree_1 exec('master.dbo.xp_dirtree '''+@bak_path+''',0,1')
select @createfolder=isnull(@createfolder,'')+'exec master.dbo.xp_cmdshell ''md '+@bak_path+''+name+''',no_output '+char(13)
from @t as a left join @dirtree_1 as b on a.name=b.subdirectory and b.files=0 and depth=1 where  b.id is null
--獲取需要創建的文件夾-------------------end
 
 
--生成處理過期備份的sql語句-------------start
if @overdueDay>0
begin
    insert into @dirtree_2(subdirectory,depth,files) exec('master.dbo.xp_dirtree '''+@bak_path+''',0,1')
    if @baktype =0 
    delete from @dirtree_2 where depth=1 or files=0 or charindex('_Full_bak_',subdirectory)=0 
    if @baktype =1 
    delete from @dirtree_2 where depth=1 or files=0 or charindex('_Diff_bak_',subdirectory)=0 
    if @baktype=2
    delete from @dirtree_2 where depth=1 or files=0 or charindex('_Log_bak_',subdirectory)=0 
    if exists(select 1 from @dirtree_2)
    delete from @dirtree_2 where isdate(
            left(right(subdirectory,19),8)+' '+ substring(right(subdirectory,20),11,2) + ':' +  
            substring(right(subdirectory,20),13,2) +':'+substring(right(subdirectory,20),15,2) 
            )=0
    if exists(select 1 from @dirtree_2)
    update @dirtree_2 set dbname = case when @baktype=0 then left(subdirectory,charindex('_Full_bak_',subdirectory)-1)
        when @baktype=1 then left(subdirectory,charindex('_Diff_bak_',subdirectory)-1) 
        when @baktype=2 then left(subdirectory,charindex('_Log_bak_',subdirectory)-1) 
        else '' end    
        ,baktime=left(right(subdirectory,19),8)+' '+ substring(right(subdirectory,20),11,2) + ':' +  
            substring(right(subdirectory,20),13,2) +':'+substring(right(subdirectory,20),15,2) 
    from @dirtree_2 as a
    delete @dirtree_2 from @dirtree_2 as a left join @t as b on b.name=a.dbname where b.id is null
    update @dirtree_2 set isLastbak= case when (select max(baktime) from @dirtree_2 where dbname=a.dbname)=baktime 
    then 1 else 0 end from @dirtree_2 as a
    select @delbak=isnull(@delbak,'')+'exec master.dbo.xp_cmdshell ''del '+@bak_path+''+dbname+'\'
    +subdirectory+''',no_output '+char(13) from @dirtree_2 where isLastbak=0 and datediff(day,baktime,getdate())>@overdueDay
end
--生成處理過期備份的sql語句--------------end
 

begin try
    print(@createfolder)  --創建備份所需文件夾
    exec(@createfolder)   --創建備份所需文件夾
end try
begin catch
    print 'err:'+ltrim(error_number())
    print 'err:'+error_message()
    return
end catch
 
 
select @i=1 ,@maxid=max(id) from @t
while @i<=@maxid
begin
    select @bak_sql=''+char(13)+'backup '+ case when @baktype=2 then 'log ' else 'database ' end
            +quotename(Name)+' to disk='''+@bak_path + Name+'\'+
            Name+ case when @baktype=0 then '_Full_bak_' when @baktype=1 then '_Diff_bak_' 
            when @baktype=2 then '_Log_bak_' else null end + case when @compression=1 then 'compression_' else '' end+
            replace(replace(replace(convert(varchar(20),getdate(),120),'-',''),' ','_'),':','')+
            case when @baktype=2 then '.trn' when @baktype=1 then '.dif' else '.bak' end +'''' 
            + case when @compression=1 or @baktype=1 then ' with ' else '' end
            + case when @compression=1 then 'compression,' else '' end
            + case when @baktype=1 then 'differential,' else '' end
            + case when @compression=1 or @baktype=1 then ' noformat' else '' end 
    from @t where id=@i
    set @i=@i+1
    begin try
        print(@bak_sql)--循環執行備份
        exec(@bak_sql) --循環執行備份
    end try
    begin catch
        print 'err:'+ltrim(error_number())
        print 'err:'+error_message()
    end catch
end
 
begin try
    print(@delbak)   --刪除超期的備份
    exec(@delbak)    --刪除超期的備份
end try
begin catch
    print 'err:'+ltrim(error_number())
    print 'err:'+error_message()
end catch

檢查語句是否可以執行:

exec sp_backupdatabase 'H:\Test_bf', '0','3','Test','14','0'

二、設置SQL SERVER 代理自啓動,創建作業以及計劃 

如果不懂,請百度一下詳細操作步驟

參照說明文檔《生產端數據庫配置說明(附:point-in-time數據恢復方法)》

三、執行以下語句可以還原到時間節點

--a) 備份當前數據庫的事務日誌:
BACKUP LOG [Test] TO disk= N'H:\Test_bf\log\TESTlog3.bak' WITH NORECOVERY
--b) 恢復一個誤刪除之前的完全備份:
RESTORE DATABASE [Test] FROM DISK = N'H:\Test_bf\Test\Test_Full_bak_20191016_134500.bak' WITH NORECOVERY,  REPLACE
--c) 將數據庫恢復至誤刪除之前的時間點:
RESTORE LOG [Test] FROM  DISK = N'H:\Test_bf\log\TESTlog3.bak' WITH   STOPAT = N'2019/10/16 13:50' , RECOVERY

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章