1,使用SQL最簡單備份,還原數據庫
- /* 備份 */
- backup database Test to disk='D:/Test.bak'
- /* 還原 */
- restore database Test from disk='D:/Test.bak'
2,爲了方便以後的使用,開始對語句進行簡單的封裝->存儲過程
1,備份
- /*******************************************************
- 備份數據庫
- *******************************************************/
- if exists(select 1 from sys.procedures where name='sp_BackupDB')
- drop procedure sp_BackupDB
- go
- create procedure sp_BackupDB
- @savePath nvarchar(4000) -- 備份數據庫保存位置(目錄)
- ,@dbName nvarchar(4000) -- 需要進行備份的數據庫
- ,@bakName nvarchar(4000) -- 備份文件的名稱(不含擴展名)
- as begin
- declare @sql nvarchar(4000)
- /* 驗證路徑 */
- if(charindex('/',reverse(@savePath))!=1) begin
- set @savePath=@savePath+'/'
- end
- /* 拼SQL並執行 */
- set @sql='backup database '+@dbName+' to disk='''+@savePath+@bakName+'.bak'''
- exec sp_executesql @sql
- /* 返回執行結果(1=成功,0=失敗) */
- if(@@error=0) begin
- return 1
- end
- return 0
- end
2,還原
- /*******************************************************
- 還原數據庫
- *******************************************************/
- if exists(select 1 from sys.procedures where name='sp_RestoreDB')
- drop procedure sp_RestoreDB
- go
- create procedure sp_RestoreDB
- /* 數據庫還原後的保存位置(目錄)(使用系統默認保存位置:-1) */
- @savePath nvarchar(4000)
- ,@backFile nvarchar(4000) -- 需要還原的數據庫備份文件
- ,@defaultName nvarchar(4000) -- 數據庫原始名稱(備份的原數據庫名稱)不包含擴展名
- /* 爲數據庫重命名(使用數據庫默認名稱:-1)不包含擴展名
- 如果目錄已存在該名稱的數據庫,將會被覆蓋 */
- ,@dbName nvarchar(4000)
- as begin
- declare @newName nvarchar(4000),@sql nvarchar(4000)
- /* 獲取數據庫名稱 */
- if(@dbName='-1') begin
- set @newName=@defaultName
- end else begin
- set @newName=@dbName
- end
- /* 結束所有對當前數據庫的連接 */
- if exists(select 1 from sys.sysprocesses where dbid=db_id(@defaultName)) begin
- declare #cs_spid cursor -- 聲明遊標
- for
- select #cs_spid=convert(varchar,spid) from sys.sysprocesses where dbid=db_id(@defaultName)
- open #cs_spid
- declare @spid varchar(20)
- fetch next from #cs_spid into @spid -- 賦值並前進到下一條
- while(@@fetch_status=0) begin -- 在fetch失敗前執行
- exec ('kill '+@spid) -- 結束對操作庫的連接(exec執行SQL語句1)
- fetch next from #cs_spid into @spid
- end
- close #cs_spid
- deallocate #cs_spid -- 釋放遊標
- end
- /* 創建執行語句 */
- set @sql='restore database '+@newName+' from disk='''+@backFile+''' with replace'
- if(@savePath!='-1') begin
- -- 驗證路徑
- if(charindex('/',reverse(@savePath))!=1) begin
- set @savePath=@savePath+'/'
- end
- set @sql=@sql+', move '''+@defaultName+''' to '''+@savePath+@newName+'.mdf'''
- set @sql=@sql+', move '''+@defaultName+'_log'' to '''+@savePath+@newName+'_log.ldf'''
- end
- /* 執行操作 */
- exec sp_executesql @sql -- (exec執行SQL語句2)
- /* 返回執行結果(1=成功,0=失敗) */
- if(@@error=0) begin
- return 1
- end
- return 0
- end