USE [master] GO /****** 对象: StoredProcedure [dbo].[DataBaseRestore] 脚本日期: 12/18/2015 14:17:11 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[DataBaseRestore] AS declare @device varchar(255) declare @path varchar(255) declare @dbname varchar(255) declare @filename varchar(255) declare @cmd varchar(255) set @dbname = 'SmartPas' set @path = 'D:database' --备份文件存储位置 set @filename = @dbname+'_Ts_'+ convert(char(8),getdate(),112)+substring(replace(convert(char(9),getdate(),114),':',''),0,3)+'.bak' set @device=@path + @filename declare @sql nvarchar(4000),@par nvarchar(1000) if not exists( select * from master..sysdatabases where name=@dbname ) begin --select @flag='db not exist' /*数据库不存在*/ return 2 end else begin --存在数据库就判断文件是否存在 declare @num int --申明一个接受返回值的变量 EXEC xp_fileexist @device ,@num output -- 执行文件存在否的验证 存在返回1 不存在返回0 if(@num = 1) --如果存在就执行还原 begin --begin tran tDeal --begin try exec ('alter database '+@dbname+' set offline WITH ROLLBACK IMMEDIATE;') select @sql='RESTORE DATABASE @db_name FROM DISK=@filename with ' select @sql=@sql +' replace' select @par='@db_name nvarchar(128),@filename nvarchar(260)' execute sp_executesql @sql,@par,@db_name=@dbname,@filename=@device exec ('alter database '+@dbname+' set online with rollback IMMEDIATE;') --删除备份文件(这句可以去掉) --set @cmd = 'del ' + @device --exec master..xp_cmdshell @cmd --end try --begin catch --rollback tran tDeal --return 0 --end catch end end