SQL Server – How to Solve SIDs Mismatching or Orphaned Users

sql serversql-server-2008-r2

I moved and restored a database from a backup into another SQL Server 2008R2 about a year ago. I wasn't aware of the concept of orphaned users. From what I understood, is that we can end up having mistmatched SIDs? So I run the following below query and I see that sid names are not the same for the server and the database for the same login user. So far, users are not complaining but how would I fix this? is there any stored procedure that list them for me? or what problems that I could be facing if I leave everything like it is.

select d.name, d.sid, s.name, s.sid
from sys.database_principals d 
full join sys.server_principals s
on d.principal_id = s.principal_id

Any advice is much appreciated.

Best Answer

There are a couple of possibilities.

First if the orphaned user is a windows login/group (type U or G) then no problem.

-- If the login doesn't currently exist on the server
CREATE LOGIN [Windows Account] FROM WINDOWS;
-- Fix the user
USE dbname
ALTER USER [user name] WITH LOGIN = [Windows Account];

If it's a "SQL Login" (type S) and the login exists then again no problem.

-- Fix the user
USE dbname
ALTER USER [user name] WITH LOGIN = [Windows Account];

If the login does not exist for a "SQL Login" then you have to create the login and that will require knowing the password.

-- Create the login
CREATE LOGIN [login name] WITH PASSWORD = '<strong password>';

Don't forget to make sure your password meets your windows policy requirements. If you still have the old server you can copy the login pretty easily from the other server including the password by getting the HASH of the password from the other server. (There may be some issues depending on if the two servers are different versions).

I did a post on this here: http://sqlstudies.com/2013/03/25/how-do-i-move-a-sql-login-from-one-server-to-another-without-the-password/