Kill only user processes in SQL Server

余生颓废 提交于 2020-05-13 14:20:12

问题


We have users that forget to close their access queries that use our SQL 2014 databases. When this happens it prevents the tables they are accessing from being rebuilt over night. Is there any way to Kill these users and not kill the system processes. From what I've read system processes are not only limited to SPID >50.


回答1:


Killing user processes based on spid>=50 seems to be not reliable.

From Adam Machanic:Smashing a DMV Myth: session_id > 50 == User Process

A recent conversation on an MVP mailing list revealed that this magic number, while perhaps once a legitimate filter, is certainly not safe to use in SQL Server 2005 or SQL Server 2008. Several system features can--and will--use session IDs greater than 50, because there is simply not enough room otherwise.

Examples include:

  • Large servers that use soft NUMA, because there is one checkpoint and lazy writer thread per NUMA node
  • Asynchronous statistics updating, again (and especially) on larger servers
    Database mirroring, especially if a large number of databases are involved
  • Service Broker activation, when a large number of activation tasks are being used

And there may be other cases as well. The point is, the number 50 is no longer a valid way to filter out system session IDs.

so your options are

SELECT *
FROM sys.dm_exec_sessions
WHERE
    is_user_process = 1

SELECT *
FROM sys.sysprocesses
WHERE
    hostprocess > ''

You can use above queries to get spids/session other than system and use kill command to kill them




回答2:


I think a combination of using sp_who and KILL should be possible, looking at Login name, hostname, etc. from sp_who




回答3:


We have users that forget to close their access queries that use our SQL 2014 databases. When this happens it prevents the tables they are accessing from being rebuilt over night.

You can put your database in single user mode (with rollback immediate) and then in multi user before you start your maintenance. All user transactions will be rolled back.




回答4:


This stored procedure works and kills hanging access queries and doesn't kill system processes.

DECLARE @v_spid INT
DECLARE c_Users CURSOR
FAST_FORWARD FOR
SELECT SPID
FROM master..sysprocesses (NOLOCK)
WHERE spid>50 
AND status='sleeping' 
AND DATEDIFF(mi,last_batch,GETDATE())>=60
AND spid<>@@spid


OPEN c_Users
FETCH NEXT FROM c_Users INTO @v_spid
WHILE (@@FETCH_STATUS=0)
BEGIN
PRINT 'KILLing '+CONVERT(VARCHAR,@v_spid)+'...'
EXEC('KILL '+@v_spid)
FETCH NEXT FROM c_Users INTO @v_spid
END

CLOSE c_Users
DEALLOCATE c_Users


来源:https://stackoverflow.com/questions/45843709/kill-only-user-processes-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!