How to Find and Fix Orphaned Users in SQL Server


After theĀ  migration of SQL Server databases we have to find the orphan users In SQL Server & need to fix them using below queries:-


EXEC sp_change_users_login 'Report'

-- Use below code to fix the issue of Orphan Users

DECLARE @username varchar(25)
DECLARE fixusers CURSOR
FOR
SELECT UserName = name FROM sysusers
WHERE issqluser = 1 and (sid is not null and sid <> 0x0)
and suser_sname(sid) is null
ORDER BY name
OPEN fixusers
FETCH NEXT FROM fixusers
INTO @username
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC sp_change_users_login 'update_one', @username, @username
FETCH NEXT FROM fixusers
INTO @username
END
CLOSE fixusers
DEALLOCATE fixusers

 

Leave a Reply

Your email address will not be published. Required fields are marked *