编程实现备份和还原数据库[2]

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 bergn 的 blog

 +case when @overexist=1 and @retype in('db','dbnor') then ',replace' else '' end
 +case @retype when 'dbnor' then ',norecovery' else ',recovery' end
 +case isnull(@password,'') when '' then '' else ',password='''+@password+'''' end
 
--添加移动逻辑文件的处理
if @retype='db' or @retype='dbnor'
begin
 --从备份文件中获取逻辑文件名
 declare @lfn nvarchar(128),@tp char(1),@i int,@s varchar(1000)
 
 --创建临时表,保存获取的信息
 create table #tb(ln nvarchar(128),pn nvarchar(260),tp char(1),fgn nvarchar(128),sz numeric(20,0),msz numeric(20,0))
 --从备份文件中获取信息
 set @s='restore filelistonly from disk='''+@bkfile+''''
  ++case isnull(@password,'') when '' then '' else ' with password='''+@password+'''' end
 insert into #tb exec(@s)
 declare #f cursor for select ln,tp from #tb
 open #f
 fetch next from #f into @lfn,@tp
 set @i=0
 while @@fetch_status=0
 begin
  select @sql=@sql+',move '''+@lfn+''' to '''+@dbpath+@dbname+cast(@i as varchar)
   +case @tp when 'd' then '.mdf''' else '.ldf''' end
   ,@i=@i+1
  fetch next from #f into @lfn,@tp
 end
 close #f
 deallocate #f
end
 
--关闭用户进程处理
if @overexist=1 and @killuser=1
begin
 declare hcforeach cursor for
 select s='kill '+cast(spid as varchar) from master..sysprocesses
 where dbid=db_id(@dbname)
 exec sp_msforeach_worker '?'
end
 
--恢复数据库
exec(@sql)
 
go
邹建说:
说白了,就是备份数据库和还原数据库的sql语句的应用:
 
--备份
backup database 数据库 to disk='c:\你的备份文件名'
 
--还原
restore database 数据库 from disk='c:\你的备份文件名'
 

ps:邹建老大真是我的偶像阿!

本文关键:编程实现备份和还原数据库
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top