代码改变世界

SQL 语句还原SQL Server数据库

2011-12-05 11:00  OOA  阅读(246)  评论(0编辑  收藏  举报
/*
断开所有用户打开的连接
*/
use master--一定要有这个
go

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_killspid]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[p_killspid]
GO

create proc p_killspid--创建存储过程
@dbname sysname --要关闭进程的数据库名
as 
declare @s nvarchar(1000)
declare tb cursor local for
select s='kill '+cast(spid as varchar)
from master..sysprocesses 
where dbid=db_id(@dbname)

open tb 
fetch next from tb into @s
while @@fetch_status=0
begin
exec(@s)
fetch next from tb into @s
end
close tb
deallocate tb
go

--用法 
exec p_killspid 'lq4'--调用存储过程 这里的hj为数据库名

--恢复数据库.
RESTORE DATABASE hj FROM disk='d:\LQ_db_201112020200.BAK' --备份数据的位置

--完成后,删除存储过程

drop proc p_killspid