Click here to Skip to main content
15,886,689 members
Articles / Database Development / SQL Server
Tip/Trick

Deleting Users With No Database Mappings

Rate me:
Please Sign up or sign in to vote.
4.47/5 (4 votes)
16 Jan 2016CPOL 6.4K   5  
A small script to remove old user accounts

Introduction

I have recently had a need to play around with one of my customers databases to assess possible performance improvements in isolation of their systems. After my job was done (reducing some stored procedures execution times from hours to minutes by dropping CURSORs in exchange for set-based approach and CTEs), I have diligently deleted all those databases and destroyed any remaining backups. However, inadverntly, I was left with a large number of user accounts without any database mappings. So, I have created this little script to remove each such login.

SQL
CREATE TABLE #tempww
  (
    LoginName NVARCHAR(MAX) ,
    DBname NVARCHAR(MAX) ,
    Username NVARCHAR(MAX) ,
    AliasName NVARCHAR(MAX)
  );

INSERT  INTO #tempww
        EXEC master..sp_MSloginmappings; 

DECLARE @usr NVARCHAR(MAX);
DECLARE @sql NVARCHAR(MAX);

DECLARE UWND CURSOR FAST_FORWARD
FOR
  SELECT  T.LoginName
  FROM    #tempww T
  JOIN    sys.syslogins SL
          ON T.LoginName = SL.name
  WHERE   SL.status = 9
          AND SL.isntuser = 0
          AND T.DBname IS NULL;

-- process
OPEN UWND;
FETCH NEXT FROM UWND INTO @usr;
WHILE @@FETCH_STATUS = 0
  BEGIN
    SET @sql = N'DROP LOGIN [' + @usr + N']';
    EXEC sys.sp_executesql @sql; 
    FETCH NEXT FROM UWND INTO @usr;
  END;
CLOSE UWND;
DEALLOCATE UWND;

-- cleanup
DROP TABLE #tempww;

First, I create a temporary table to retrieve all existing user mappings, Then I use a CURSOR to iterate through all found records, which are not NT Accounts, are active, and have no database mapped. For each found such login, I execute a DROP LOGIN command, and cleanup after the process.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect BI Software, Inc.
United States United States
A seasoned IT Professional. Programming and data processing artist. Contributor to StackOverflow.

Comments and Discussions

 
-- There are no messages in this forum --