When dropping a SQL Server 2008 login as part of integration test execution I sometimes get the following error:
System.Data.SqlClient.SqlException: Cou
OK, here's the script I came up with, which worked for me. Note that you need to be a member of the processadmin server role to find and kill the connection and a member of securityadmin to drop the login. (Of course, sysadmin can do anything.)
DECLARE @loginNameToDrop sysname
SET @loginNameToDrop = '<victim login ID>';
DECLARE sessionsToKill CURSOR FAST_FORWARD FOR
SELECT session_id
FROM sys.dm_exec_sessions
WHERE login_name = @loginNameToDrop
OPEN sessionsToKill
DECLARE @sessionId INT
DECLARE @statement NVARCHAR(200)
FETCH NEXT FROM sessionsToKill INTO @sessionId
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Killing session ' + CAST(@sessionId AS NVARCHAR(20)) + ' for login ' + @loginNameToDrop
SET @statement = 'KILL ' + CAST(@sessionId AS NVARCHAR(20))
EXEC sp_executesql @statement
FETCH NEXT FROM sessionsToKill INTO @sessionId
END
CLOSE sessionsToKill
DEALLOCATE sessionsToKill
PRINT 'Dropping login ' + @loginNameToDrop
SET @statement = 'DROP LOGIN [' + @loginNameToDrop + ']'
EXEC sp_executesql @statement
User can be deleted after killing the session by identifying the session_id of the user.
SELECT session_id
FROM sys.dm_exec_sessions
WHERE login_name = 'test'
KILL 69 --69 is session_id here, you may get different id
Now you can delete the login simply by executing the below query (or) by using sql server management studio options.
DROP LOGIN 'test'
In SqlServer Studio on the Master DB.
Use the command sp_who2 to list the opened sessions.
In the list find the spid for your user - there may be more than one - e.g. 999
Use kill and the spid to close all the sessions e.g.: kill 999
Then DROP LOGIN [theuser]
ALTER DATABASE [DATABASE_NAME]
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE
as SqlACID said, or you could find all processes and kill one at time and then drop user
This may not always be applicable but I've just restarted the SQL server from services. That cleared up any open connections.
If you know what database they will be connected to, you could set the database to single user mode, with rollback immediate, that'll drop their sessions.