• Attaching and restoring databases from one server instance to another are common tasks executed by a DBA.If we move our database to another SQL Server instance through any process, the new server might or might not have the same logins and the SIDs of these logins would probably be different from the SIDs of these logins in the original server. What this means is that, the sysusers table in the moved database has SIDs that are not matched with the login info in the master database on this new server. Therefore we get orphaned users

    Once the Database is restored on the new instance. Run the below commands to troubleshoot and fix the issue.

    -Command to generate list of orphaned users

    USE <DBNAME>

    GO

    sp_change_users_login @Action='Report'

    GO

    --Command to map an orphaned user

    EXEC sp_change_users_login 'Auto_Fix', '<Username>'

    GO

    If a login name does not exists, you would have to create it first before doing the mapping. A quick way to do this is to use the following command which will create the login and then map the login to the user

    --Command to map an orphaned user to a login that is not present but will be created

    EXEC sp_change_users_login 'Auto_Fix', '<Username>', null,'<pwd>'

    GO