65.9K
CodeProject is changing. Read more.
Home

Deleting Users With No Database Mappings

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.47/5 (4 votes)

Jan 17, 2016

CPOL
viewsIcon

6470

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.

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.