use gyjlbigfootmis
go
if exists (select * from sysobjects where [name]='KYMP_还原数据库' and [type]='P')
begin
drop procedure KYMP_还原数据库
end
go
create procedure KYMP_还原数据库
@databasename varchar (1000), /* 数据库名称 */
@backuppath varchar(2000), /* 备份文件路径,还原的设备 */
@filepath varchar(2000), /* 还原文件路径,如果为空就使用默认路径 */
@filename varchar(1000), /* 还原名称,即为物理文件名,后缀自动加*/
@datapdw varchar(100) /* 密码 */
as
if (@databasename is null or @databasename='') or (@backuppath is null or @backuppath='') --- 判断数据库名称与还原设备
begin
print '必要的参数未之名,数据库名称或备份设备路径不对。'
return
end
if (not exists(select * from sys.databases where [name]=@databasename)) --- 判断数据库是否存在
begin
print '找不到数据库'
return
end
/*
if()
begin
print '找不到设备文件'
return
end
*/
declare @exec_sql varchar(5000), /* 执行还原的语句 */
@base_mdf varchar(100), /* 备份设备的数据文件类型名 */
@base_ldf varchar(100), /* 备份设备的日志文件类型名 */
@old_mdf_dir varchar(1000), /* 原数据库数据物理文件路径 */
@old_ldf_dir varchar(1000), /* 原数据库日志物理文件路径 */
@old_mdf_name varchar(1000), /* 原数据库数据物理文件名 */
@old_ldf_name varchar(1000), /* 原数据库日志物理文件名 */
@search_sql varchar(1000) /* 查找原数据库文件名语句 */
set @search_sql='select * from '+@databasename+'.dbo.sysfiles'
select * into #tmp_1 from master..sysfiles where 1=2 -- 取原来的数据库物理文件信息
insert into #tmp_1 exec (@search_sql)
select * from #tmp_1
create table #t(LogicalName varchar(255), PhysicalName varchar(255),
Type varchar(20), FileGroupName varchar(255), Size varchar(20),
MaxSize varchar(20), Fileld VARCHAR(20), CreateLSN VARCHAR(20),
DropLSN VARCHAR(20), Uniqueld uniqueidentifier, ReadOnlyLSN VARCHAR(20),
ReadWriteLSN VARCHAR(20), BackupSizeInBytes VARCHAR(255), SourceBlockSize VARCHAR(20),
FileGroupld VARCHAR(20), LogGroupGUID VARCHAR(20), DifferentialBaseLSN VARCHAR(20),
DifferentialBaseGUID uniqueidentifier, IsReadOnly VARCHAR(20), IsPresent VARCHAR(20))
insert #t exec(' RESTORE FILELISTONLY from disk='''+@backuppath+'''')
select @base_mdf=[logicalname] from #t where [Fileld]=1 and [type]='D'
select @base_ldf=[logicalname] from #t where [Fileld]=2 and [type]='L'
drop table #t
set @exec_sql=''
set @exec_sql=@exec_sql+'Alter Database gyjlbigfootmis Set Offline with Rollback immediate '
+'/* 断开所有连接并回滚所有控制事务,置数据库为不可连接状态*/ '
+'restore database gyjlbigfootmis from disk='''+@backuppath+''''+' with replace, '
+'move '''+@base_mdf+''' to '''+@filepath+@filename+'_data.mdf'''
+',move '''+@base_ldf+''' to '''+@filepath+@filename+'_ldf.ldf '''
+' Alter Database gyjlbigfootmis Set OnLine With rollback Immediate '
+' /* 置数据库为可连接状态,回滚事务*/'
--select @exec_sql
exec (@exec_sql)
go
exec KYMP_还原数据库 'gyjlbigfootmis','H:/工作/gybigfootmis_backup_201002251800/gybigfootmis_backup_201002251800.bak','e:/mssql/data/','gyjlbigfootmis1',''