远程关闭数据库的某一实例?

来源:互联网 发布:万序软件有 编辑:程序博客网 时间:2024/05/21 22:53

--断开指定库的所有用户连接(在master数据库中进行)
use master
go

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

create proc sp_KillSpid
@dbname sysname  --要断开连接的数据库名
as 
declare @s nvarchar(1000)
declare tb cursor local
for
select N'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 sp_KillSpid  'aa'