I want to create a cursor (without creating a temp table) to get all orphan users in my SQL Server instances. Here is what I've come up with:
Declare @Orphan_users table (username sysname)
DECLARE @orphan_users_cursor CURSOR
set @orphan_users_cursor = cursor
FOR
select * from (
insert into @Orphan_users
set EXEC SP_MSFOREACHDB' USE [?]
SELECT dp.name
FROM sys.database_principals AS dp
LEFT JOIN sys.server_principals AS sp
ON dp.SID = sp.SID
WHERE sp.SID IS NULL
AND authentication_type_desc = ''INSTANCE'''--)
OPEN @orphan_users_cursor
FETCH NEXT FROM @orphan_users_cursor INTO @Orphan_users
Best Answer
I think your table should also include the database name, otherwise once you identify a user that is abandoned in some database on your system, how are you going to find them?
Anyway here is a way to do it by building a single query rather than executing a query database by database (and relying on a system procedure that is undocumented, unsupported, and has community replacements because it's so buggy). It isn't better or faster, just easier to understand and troubleshoot, IMHO.