Sometime when we restore the database from a backup file in SQL Server 2005, after that some logins are not allowed access to database. error like can’t login user ‘null’ in the database occur when connecting using code.
This happens because while restoring the database backup the login was not linked with the user name it was associated in the database whose backup we are using. To login into the DB using that login you need to assign that login a username.
@ work I need to restore databases many times and use them to debug to solve the issue. So I used to get this problem every time I restore the backup. Earlier to solve this issue, I used to use brut force method to resolve this like deleting the troubled login from the “Database\Security\Users” and deleting the schema related to this login. Then adding the same login again to “Database\Security\Users” . This used to solve my problem.
Microsoft SQL Server 2005 provide a procedure to solve this issue, which is in fact the right way to it. sp_change_users_login this sp is intended to relink the orphaned login with their user name. following are the parameters to this procedure.
@Action: this parameter indicate what action to perform. it can be one of the 3 values
- Reports : Returns all the orphaned logins in the database
- Auto_Fix : Fixes the given login and sets the username to the user with the same name in database, if a user with same name is not found then a new entry in sys.database_principals table and the newly created entry is linked with the provided login.
- Update_One : updates the given login with the login name provided.
The Report argument will return any orphaned users within the current database.
Above example displays usage of Auto_fix
The above command will update the sampleuser users login to sampleUser.
Following are some references:
Hope this helps