找出活动的SQL连接并Kill掉的代码

发布时间:2020-05-09编辑:脚本学堂
找出活动的SQL连接并Kill掉的代码

找出正在执行的SQL
 

复制代码 代码如下:
select
    db_name(dbid) as [Database Name],
    count(dbid) as [No Of Connections],
    loginame as [Login Name]
from
    sys.sysprocesses
where
    dbid > 0
group by
    dbid, loginame

停止SQL执行:
 

复制代码 代码如下:

set nocount on
declare @databasename varchar(100)
declare @query varchar(max)
set @query = ''

set @databasename = 'xxx'
if db_id(@databasename) < 4
begin
 print 'system database connection cannot be killeed'
return
end

select @query=coalesce(@query,',' )+'kill '+convert(varchar, spid)+ '; '
from master..sysprocesses where dbid=db_id(@databasename)

if len(@query) > 0
begin
print @query
 exec(@query)
end

源文地址:How to find the active SQL connections and kill them