Technical Article

Dynamically Drop a User From Your SQL Instance

,

  • Copy the code into a new query window.
  • Edit the SET @UserLogin variable as required for the server login.
  • Execute the script.

Simple

DECLARE @Cursor CURSOR
DECLARE @DatabaseName VARCHAR(100)
DECLARE @UserLogin VARCHAR(100)
DECLARE @Message VARCHAR(100)

--Enter user server login:
SET @UserLogin = 'domain\username'

--Temp table for information purposes only
IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE ID = OBJECT_ID(N'tempdb..##DropUserCount'))
DROP TABLE ##DropUserCount

CREATE TABLE ##DropUserCount
(
[LoginFound] INT
)

--Remove user from each database
SET @Message = 'User found in and removed from database: '
SET @Cursor = CURSOR FOR
SELECT
[name]
FROM
sys.databases
WHERE
[state] <> 6 --6 = Offline
ORDER BY
[name]

OPEN @Cursor
FETCH NEXT FROM @Cursor INTO
@DatabaseName

WHILE (@@FETCH_STATUS = 0)
BEGIN

DECLARE @SQL NVARCHAR(MAX)
SET @SQL = 
'
USE [' + @DatabaseName + ']

SET NOCOUNT ON
DECLARE @LocalUser VARCHAR(200)

IF(
SELECT
COUNT(0)
FROM
sys.server_principals serv
JOIN sys.database_principals dbs
ON serv.[sid] = dbs.[sid]
WHERE
serv.[name] = ''' + @UserLogin + '''
) > 0

BEGIN
SELECT
@LocalUser = dbs.[name]
FROM
sys.server_principals serv
JOIN sys.database_principals dbs
ON serv.[sid] = dbs.[sid]
WHERE
serv.[name] = ''' + @UserLogin + '''

INSERT INTO ##DropUserCount ([LoginFound]) VALUES (''1'')

EXEC sp_dropuser @LocalUser
PRINT ''' + @Message + @DatabaseName + '.''
END

'

--PRINT @SQL
EXEC (@SQL)
FETCH NEXT FROM @Cursor INTO
@DatabaseName

END

CLOSE @Cursor
DEALLOCATE @Cursor

IF(SELECT SUM([LoginFound]) FROM ##DropUserCount) IS NULL
PRINT 'User database logins not found.'

--Remove login from server
IF (SELECT COUNT(0) FROM sys.syslogins WHERE [name] = @UserLogin) > 0
BEGIN
SET @SQL = 'DROP LOGIN [' + @UserLogin + ']'
EXEC (@SQL)
PRINT 'User login dropped from server.'
END
ELSE
BEGIN
PRINT 'User login to server not found.'
END

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating