Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop SQL login even while logged in

When dropping a SQL Server 2008 login as part of integration test execution I sometimes get the following error:

System.Data.SqlClient.SqlException: Could not drop login 'SomeTestUser' as the user is currently logged in.

I don't care if it's logged in - I still want to drop it. What's the easiest way to do this?

like image 327
EMP Avatar asked Feb 11 '11 03:02

EMP


People also ask

Can't drop login as the user is currently logged in mssql?

Microsoft SQL Server Error 15434 This error generates when a login has made a connection to the SQL Server Instance and you are trying to drop the same login. Solution to fix this issue is to close all sessions which are opened by this login and then drop it.

How do I disable multiple logins in SQL Server?

1 Answer. Show activity on this post. You need to dynamically build a script that will do that. SELECT N'ALTER LOGIN ' + QUOTENAME(sp.name) + N' DISABLE;' FROM sys.

How do I stop SQL Management Studio login?

You can use the DENY VIEW ANY DATABASE command for the particular user(s). This is a new feature available in SQL Server 2008. It prevents the user from seeing the system catalog (sys. databases, sys.


2 Answers

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 
like image 128
EMP Avatar answered Oct 04 '22 12:10

EMP


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]

like image 38
pasx Avatar answered Oct 04 '22 10:10

pasx