In the scenario where the login is got deleted , the orphan users can be fixed by dropping the user from the databases using the below script.
DROP USER TestwindowsSome time the above script may throw an error saying that the users owns a schema.Find out the schema owned by this login by querying the catalog view sys.schema and mapping the principal_id to sys.database_principals.Either drop these schemas or change the ownership based on your environment. To change the ownership of the schema ,use the below command
ALTER AUTHORIZATION ON SCHEMA::SchemaName TO NewUserName;
In the scenario where database restored in a different environment, we can fix the SID mismatch between the sys.server_principals and sys.database_principals by using the system stored procedure sp_change_users_login. For example you have login Mydomain\Lastname.Firstname in two instances namely INST1 and INST2. This login is associated with the user TestWindowsUser with db_owner right on one of the database (MyDb) in INST1. Now you have taken backup of MyDb and restored it on the INST2 and Mydomain\Lastname.Firstname will not be able to access the restored database as its SID is not matching with sys.server_principals SID . To fix this issue we can run the below command on the restored database.
USE MyDb
GO
Exec sp_change_users_login 'update_one', 'TestWindowsUser', 'Mydomain\Lastname.Firstname'
Note: This is a deprecated feature in SQL server 2008 and you can use alter user as given below
ALTER USER TestWindowsUser WITH LOGIN [Mydomain\Lastname.Firstname]
If you liked this post, do like my page on FaceBook