/*********************************************************************************************
Function:數據庫還原(支持自動覆蓋現有數據庫及自動創建相關路徑)
Author:Bean
Date:2012-09-24
注:感謝“小愛”提供幫助
*********************************************************************************************/
use master
go
if OBJECT_ID('sp_restore','P') is not null drop proc sp_restore
go
create proc sp_restore
@dbName varchar(128),
@crtDBName varchar(128),
@fullDBSourcePath varchar(1024),
@dbStorePath varchar(1024)
as
Begin
set nocount on
declare @result int, --定義變量用來判斷文件是否存在
@mdfPath varchar(1024),
@ldfPath varchar(1024),
@crtPath varchar(1024)
--//把'/'替換成'\'
set @fullDBSourcePath=REPLACE(@fullDBSourcePath,'/','\')
set @dbStorePath=REPLACE(@dbStorePath,'/','\')
--//得到mdf 和 ldf 生成文件地址
set @mdfPath=@dbStorePath+'\'+ @dbName+'.mdf'
set @ldfPath=@dbStorePath+'\'+ @dbName+'.ldf'
/*** 判斷路徑是否存在 ***/
exec sp_configure 'show advanced options',1;reconfigure;
exec sp_configure 'xp_cmdshell',1;reconfigure;
set @crtPath='mkdir '+replace(@dbStorePath,' ','" "')
--//創建路徑
Exec master.dbo.xp_cmdshell @crtPath,NO_OUTPUT
/*** 判斷數據庫是否存在 ***/
if exists(select 1 from sys.databases where name =@dbName)
Begin
--//備份數據庫
declare @filename varchar(1024)
--獲取文件名
set @fileName=@dbName+replace
(replace
(replace
(CONVERT(varchar, getdate(), 120 )
,'-','')
,' ','')
,':','')
+'.bak'
--開始備份
exec
(
'backup database '+@dbName+' to disk='''+@dbStorePath+'\'+@fileName+''''
)
--//斷開連接
exec
(
'alter database '+@dbName+' set single_user with rollback immediate'
)
End
/*** bak數據庫是否存在 ***/
Exec master.dbo.xp_fileexist @fullDBSourcePath,@result out
--如果存在
if @result=1
Begin
exec(
'restore database '+@dbName+
' from disk= '''+@fullDBSourcePath+''''+
' with replace ,
move '''+@crtDBName+''' to '''+@mdfPath+''','+
' move '''+@crtDBName+'_log'''+' to '''+@ldfPath+''''
)
End
Else
Begin
RaisError('Can not find bak recourse from the Database Recourse Path.',16,1);
Return;
End
End
go
--測試腳本
--master.dbo.sp_restore 'XJTLU_04201','LANDAV8','D:\Data\bak\XJTLU_042020120911123443.bak','D:\Data'
(2期)數據庫還原(支持覆蓋數據庫、自動創建相關路徑)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.