Microsoft SQL Server 查询连接数和关闭连接数

1. 查询指定数据库有哪些连接(connection)

 

复制代码
SELECT * FROM 
[Master].[dbo].[SYSPROCESSES] WHERE [DBID] 
IN 
(
  SELECT 
   [DBID]
  FROM 
   [Master].[dbo].[SYSDATABASES] 
  WHERE 
   NAME='test'  ---"test"为你要查询的数据库的名字
)
复制代码

 

 

2.查询整个数据库系统所有的数据库有多少连接,以分组统计的方式显示。

复制代码
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
复制代码

 

 

3.关闭指定数据库的连接

复制代码
set nocount on
declare @databasename varchar(100)
declare @query varchar(max)
set @query = ''

set @databasename = 'test' --“test”为数据库的名字
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
复制代码
posted @ 2020-07-02 10:09  橪然  阅读(511)  评论(0编辑  收藏  举报