Below query will get the information from all the user databases with no mapped logins.
DECLARE @sql varchar(2000),
@dbname varchar(64)
--IF OBJECT_ID('tempdb.dbo.#temp') IS NOT NULL
CREATE TABLE tempdb.dbo.#temp(
[Database Name] VARCHAR(30),
Name VARCHAR(20),
[Type] VARCHAR(1),
[Type Description] VARCHAR(20),
[SID] VARBINARY(85),
[SID Length] INT
)
DECLARE orphaned_users CURSOR FOR
SELECT d.name
FROM sys.databases d
WHERE d.database_id >4
OPEN orphaned_users
FETCH NEXT FROM orphaned_users INTO @dbname
WHILE @@FETCH_STATUS <> -1
BEGIN
SELECT @sql ='USE [@dbname]
INSERT INTO tempdb.dbo.#temp ([Database Name],Name,[Type],[Type Description],[SID],[SID Length])
SELECT
DB_NAME() As ''Database Name'',
dp.name AS ''Name'',
dp.[type] AS ''Type'',
CASE WHEN dp.[type]=''U'' THEN ''WINDOWS USER''
WHEN dp.[type]=''S'' THEN ''SQL USER''
WHEN dp.[type]=''C'' THEN ''USER MAPPED TO A CERTIFICATE''
WHEN dp.[type]=''K'' THEN ''USER MAPPED TO AN ASSYMETRIC KEY''
END AS ''Type Description'',
dp.[sid] AS ''SID'',
LEN(dp.[sid]) AS [SID Length]
FROM sys.database_principals dp
LEFT JOIN sys.server_principals sp
ON dp.[sid] = sp.[sid]
LEFT JOIN sys.certificates c
ON dp.[sid] = c.[sid]
LEFT JOIN sys.asymmetric_keys a
ON dp.[sid] = a.[sid]
WHERE sp.[sid] is null and c.[sid] is null and a.[sid] is null
AND dp.[type] in (''U'', ''S'', ''C'', ''K'')
AND dp.principal_id > 4 -- 0..4 are system users which will be ignored
AND NOT (dp.[type] = ''S'' and LEN(dp.[sid]) = 28)'
SELECT @sql = REPLACE(@sql,'@dbname',@dbname)
--PRINT (@sql)
EXEC (@sql)
FETCH NEXT FROM orphaned_users into @dbname
END
CLOSE orphaned_users
DEALLOCATE orphaned_users
SELECT 'USE '+[Database Name]+CHAR(13)+'DROP USER '+QUOTENAME(Name)+' ;' AS 'Drop Orphan Users' FROM #temp
DROP TABLE #temp
No comments:
Post a Comment