SQL语句备份和还原数据库


1,使用SQL最简单备份,还原数据库

1 /* 备份 */ 2 backup database Test to disk='D:/Test.bak' 3 /* 还原 */ 4 restore database Test from disk='D:/Test.bak'

2,为了方便以后的使用,开始对语句进行简单的封装->存储过程

(1)备份

复制代码
 1 /*******************************************************  2  备份数据库  3 *******************************************************/  4 if exists(select 1 from sys.procedures where name='sp_BackupDB')  5  drop procedure sp_BackupDB  6 go  7 create procedure sp_BackupDB  8 @savePath nvarchar(4000) -- 备份数据库保存位置(目录)  9 ,@dbName nvarchar(4000) -- 需要进行备份的数据库 10 ,@bakName nvarchar(4000) -- 备份文件的名称(不含扩展名) 11 as begin 12 declare @sql nvarchar(4000) 13 /* 验证路径 */ 14 if(charindex('/',reverse(@savePath))!=1) begin 15 set @savePath=@savePath+'/' 16  end 17 /* 拼SQL并执行 */ 18 set @sql='backup database '+@dbName+' to disk='''+@savePath+@bakName+'.bak''' 19  exec sp_executesql @sql 20 21 /* 返回执行结果(1=成功,0=失败) */ 22 if(@@error=0) begin 23 return 1 24  end 25 return 0 26 end
复制代码

(2)还原

复制代码
 1 /*******************************************************  2  还原数据库  3 *******************************************************/  4 if exists(select 1 from sys.procedures where name='sp_RestoreDB')  5  drop procedure sp_RestoreDB  6 go  7 create procedure sp_RestoreDB  8 /* 数据库还原后的保存位置(目录)(使用系统默认保存位置:-1) */  9 @savePath nvarchar(4000) 10 ,@backFile nvarchar(4000) -- 需要还原的数据库备份文件 11 ,@defaultName nvarchar(4000) -- 数据库原始名称(备份的原数据库名称)不包含扩展名 12 /* 为数据库重命名(使用数据库默认名称:-1)不包含扩展名 13  如果目录已存在该名称的数据库,将会被覆盖 */ 14 ,@dbName nvarchar(4000) 15 as begin 16 declare @newName nvarchar(4000),@sql nvarchar(4000) 17 /* 获取数据库名称 */ 18 if(@dbName='-1') begin 19 set @newName=@defaultName 20 end else begin 21 set @newName=@dbName 22  end 23 /* 结束所有对当前数据库的连接 */ 24 if exists(select 1 from sys.sysprocesses where dbid=db_id(@defaultName)) begin 25 declare #cs_spid cursor -- 声明游标 26 for 27 select #cs_spid=convert(varchar,spid) from sys.sysprocesses where dbid=db_id(@defaultName) 28  open #cs_spid 29 declare @spid varchar(20) 30 fetch next from #cs_spid into @spid -- 赋值并前进到下一条 31 while(@@fetch_status=0) begin -- 在fetch失败前执行 32 exec ('kill '+@spid) -- 结束对操作库的连接(exec执行SQL语句1) 33 fetch next from #cs_spid into @spid 34  end 35  close #cs_spid 36 deallocate #cs_spid -- 释放游标 37  end 38 /* 创建执行语句 */ 39 set @sql='restore database '+@newName+' from disk='''+@backFile+''' with replace' 40 if(@savePath!='-1') begin 41 -- 验证路径 42 if(charindex('/',reverse(@savePath))!=1) begin 43 set @savePath=@savePath+'/' 44  end 45 set @sql=@sql+', move '''+@defaultName+''' to '''+@savePath+@newName+'.mdf''' 46 set @sql=@sql+', move '''+@defaultName+'_log'' to '''+@savePath+@newName+'_log.ldf''' 47  end 48 /* 执行操作 */ 49 exec sp_executesql @sql -- (exec执行SQL语句2) 50 /* 返回执行结果(1=成功,0=失败) */ 51 if(@@error=0) begin 52 return 1 53 end 54 return 0 55 end


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM