我想修改以下内容,因为它似乎不会杀死进程 - 我认为它应该断开用户连接(这是一样的吗?)。我希望能够终止特定数据库的所有进程 - 如何修改以下内容:

create procedure [dbo].[sp_killusers](@database varchar(30))
as
----------------------------------------------------
-- * Created By David Wiseman, Updated 19/11/2006
-- * http://www.wisesoft.co.uk
-- * This procedure takes the name of a database as input
-- * and uses the kill statment to disconnect them from
-- * the database.
-- * PLEASE USE WITH CAUTION!!
-- * Usage:
-- * exec sp_killusers 'databasename'
----------------------------------------------------
set nocount on
declare @spid int
declare @killstatement nvarchar(10)

-- Declare a cursor to select the users connected to the specified database
declare c1 cursor for select request_session_id
                                from sys.dm_tran_locks
                                    where resource_type='DATABASE'
                                    AND DB_NAME(resource_database_id) = @database
open c1
fetch next from c1 into @spid
-- for each spid...
while @@FETCH_STATUS = 0
begin
      -- Don't kill the connection of the user executing this statement
      IF @@SPID <> @spid
      begin
            -- Construct dynamic sql to kill spid
            set @killstatement = 'KILL ' + cast(@spid as varchar(3))
            exec sp_executesql @killstatement
            -- Print killed spid
            print @spid
      end
      fetch next from c1 into @spid
end
-- Clean up
close c1
deallocate c1

更新

以上不起作用,即它不会终止进程。

最佳答案

我熟悉这个脚本。它会杀死所有使用数据库的 SPID,是的。您需要在正确的权限下运行它 - 不是任何用户都可以杀死 SPID。

此外,您可能有应用程序尝试维护与数据库的持久连接,因此可能会在您终止其 SPID 后不久重新连接。

关于sql-server - SQL Server : Kill Process using Stored Procedure,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1808366/

10-11 21:12