We still have quite a few Sql Server login accounts and with frequent copying & restoring, have to deal with orphaned users. I assign this script to Ctrl+0. After restoring a db I start a new query in that db then hit Ctrl+0.
The Select produces the "sp_change_users_login" statements for any orphans. I like to see what is produced & then copy / paste into the query window for executing.
Declare @usrs as Table ([usr] [varchar](50) NULL,[usid] [varbinary](250) NULL);insert @usrs execute sp_change_users_login 'Report';select 'exec sp_change_users_login ''update_one'', ' + '''' + usr + ''',' +'''' + usr + ''';' from @usrs;
Formatted:
DECLARE @usrs AS TABLE (
[usr] [varchar](50) NULL,
[usid] [varbinary](250) NULL
);
INSERT @usrs
EXECUTE sp_change_users_login 'Report';
SELECT 'exec sp_change_users_login ''update_one'', ' + '''' + usr + ''',' + '''' + usr + ''';'
FROM @usrs;