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 CURSOR
s 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;
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;
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.