if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_RestoreDb]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[p_RestoreDb]
GO
--从备份文件中获取信息
insert into #tb
exec('restore filelistonly
from disk='''+@bkfile+'''')
--将信息保存到变量中
select @logfn1=lgfn,@phyfn1=pyfn from #tb where type='D'
select @logfn2=lgfn,@phyfn2=pyfn from #tb where type='L'
--删除临时表
drop table #tb
--显示获取的信息
select @logfn1 as 逻辑数据文件名,@phyfn1 as 物理数据文件名
union all
select @logfn2 as 逻辑日志文件名,@phyfn2 as 物理日志文件名
--生成恢复的语句
declare @sql varchar(8000)
--得到SQL安装时的数据文件路径
select @phyfn1=rtrim(reverse(filename)) from master..sysfiles where name='master'
select @phyfn1=reverse(substring(@phyfn1,charindex('\',@phyfn1),8000))
--关闭用户进程处理
if @overexist=1 and @killuser=1
begin
declare @spid varchar(20)
declare #spid cursor for
select spid=cast(spid as varchar(20)) from master..sysprocesses where dbid=db_id(@redb)
open #spid
fetch next from #spid into @spid
while @@fetch_status=0
begin
exec('kill '+@spid)
fetch next from #spid into @spid
end
close #spid
deallocate #spid
end
--生成数据恢复语句,将数据库恢复到SQL数据目录下
set @sql='restore database '+@redb
+' from disk='''+@bkfile+''''
+' with move '''+@logfn1+''' to '''
+@phyfn1+@redb+'.mdf'',move '''
+@logfn2+''' to '''+@phyfn1+@redb+'.ldf'''
+case @overexist when 1 then ',replace' else '' end
exec(@sql)
go