-- Identify all Orphan Users and correct their logins.
-- List orphan users
EXEC sp_change_users_login 'Report'

-- For each orphan, link the user in the current db to an existing SQL login
DECLARE @CurrentUserName varchar(25)
DECLARE OrphanedUsers CURSOR FOR
   SELECT CurrentUserName = name 
     FROM sysusers
    WHERE issqluser = 1 
      AND (sid IS NOT NULL AND sid <> 0x0)
      AND suser_sname(sid) IS NULL
    ORDER BY name

OPEN OrphanedUsers
FETCH NEXT FROM OrphanedUsers
INTO @CurrentUserName
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC sp_change_users_login 'update_one', @CurrentUserName, @CurrentUserName
FETCH NEXT FROM OrphanedUsers
INTO @CurrentUserName
END
CLOSE OrphanedUsers
DEALLOCATE OrphanedUsers
