Drop SQL login even while logged in

前端 未结 6 1377
感动是毒
感动是毒 2021-02-05 01:25

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

System.Data.SqlClient.SqlException: Cou

相关标签:
6条回答
  • 2021-02-05 01:28

    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
    
    0 讨论(0)
  • 2021-02-05 01:31

    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'
    
    0 讨论(0)
  • 2021-02-05 01:36

    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]

    0 讨论(0)
  • 2021-02-05 01:44
    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

    0 讨论(0)
  • 2021-02-05 01:47

    This may not always be applicable but I've just restarted the SQL server from services. That cleared up any open connections.

    0 讨论(0)
  • 2021-02-05 01:50

    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.

    0 讨论(0)
提交回复
热议问题