Friday, June 05, 2009

Troubleshooting Orphaned Users in SQL Server 2005 / 2008

A couple of days ago, I was tasked with moving a database from an older server to a new souped-up box. Unfortunately the transition was not as smooth as I had hoped for. After restoring the db into the new server I started running into trouble with orphaned users.

An orphaned user is basically just that, a database user without a corresponding server login.  This usually happens when trying to restore a database into a new server, like what I was doing or accidently deleting the server login.

Luckily this issue can be solved relatively easy using the sp_change_users_login stored procedure.

First I get a list of orphaned users and their SIDs using the following procedure:

sp_change_users_login @Action='Report';

Next, I create the missing login from scratch (e.g. “NewLoginName”). The server mappings are not required as the database user roles are preserved in the database.

Then execute the stored procedure again with the following parameters:

sp_change_users_login
      @Action='Update_One',
      @UserNamePattern='dbUserName',
      @LoginName='NewLoginName';

This re-jigs the broken “dbUserName” user with the newly created Server Login “NewLoginName”.

Its worth mentioning that even though there might be a login name existing on the new server identical to the database user name, they are not the same until linked together. You can find out for sure using the above stored procedure with the “REPORT” parameter.

Finally, hereare some instances where sp_change_users_login cannot be used:

  • Cannot be used to map database users to Windows-level principals, certificates, or asymmetric keys.
  • Cannot be used with a SQL Server login created from a Windows principal or with a user created by using CREATE USER WITHOUT LOGIN.

More information:

No comments: