(Note this question asks about linking ALL Users, unlike the possible duplicate that asks about linking a single user)
I wish to move a database between two servers, I have backed the database up from the first server and done a database restore on the 2nd server, so far so good.
However our application makes use of a lot of database users that are defined in the database. These have to be linked to logins that are defined in the master database. The server I have restored the database to has all the logins defined, however they have different sids.
I am not a T-SQL expert….
I think sp_change_users_login
is part of the solution, but I can't find out how to get it to automatically link all users in the restored database to the login of the same name.
The database creation scripts we use for our application create the users and logins, however it does not specify the SID when creating the login, hence this problem. Now if I had a time machine...
(When I Google I get lots of hits, however they are mostly sites that won't let you see the answer without having to register on the site first.)
I found the following script from Microsoft KB918992 - run it on the original server and it will create a stored procedure called 'sp_help_revlogin' which generates another script to run on the destination server, creating all user accounts with the same passwords and sids. Worked wonders for our upgrade from SQL2000 to 2008.
I have a nice script that you can use to create logins from database users,which I came across after searching for this issue this script is using a stored procedure. you can find some other useful scripts here also at this url http://www.sqlserveroptimizer.com/2011/08/how-to-script-logins-from-user-database-in-sql-server-20052008-r2/
If:
Doest't work, try this:
I found it here: http://dbadiaries.com/using-sp_change_users_login-to-fix-sql-server-orphaned-users
Yes, you can do that by executing:
However if your question was can I fix all users automatically then this won't do that.
I came up with the following. It works great because it shows you:
Other solutions require you to know the orphaned user name before hand in order to fix.
The following code could run in a sproc that is called after restoring a database to another server.
Script:
Result:
*Note: The 4 that were not fixed (in my example screenshot above) did not have a corresponding User in the destination Server that the database was restored to.