Fixing Orphaned Users In SQL Server 2005

The other day i restored a QA database in compatibility level 90 (SQL Server 2005) to a production server that had SQL Server 2005 installed.  The restore went as expected however, the logins that were already there on the SQL Server had different SIDs than the users in the database that was restored.  We maintain three different environments for production databases (dev, qa and production) and in each environment the logins have different SIDs and passwords.  So after promoting the databases from one environment to another we need to re-sync the SIDs.

Now back in the days of SQL Server 2000 and earlier you needed to write a T-SQL script that allowed access to the system tables, grab the SIDS from syslogins (sysxlogins) and update the SIDs in the user database.  Now lets fast forward to SQL Server 2005… Microsoft recogonized the need to sync database users to logins and vice versa for different servers.  So in SQL Server 2005 came the stored procedure sp_change_users_login.  To find out more information on this stored procedure you can visit this site:   http://technet.microsoft.com/en-us/library/ms174378.aspx .

Here is a T-SQL script that you run in a query window to allow you to sync database users to SQL Server logins.  Now one thing to note here… make sure you run the script in the context of the database that you want to sync the users for.  Here is the script:

SET NOCOUNT ON
SET QUOTED_IDENTIFIER OFF

GO

USE <database name>
GO

DECLARE @sql varchar(100);

DECLARE curSQL CURSOR FOR
SELECT ‘EXEC sp_change_users_login ”UPDATE_ONE”, ”’ + name + ”’, ”’ + name + ””
FROM sysusers
WHERE issqluser = 1
AND suser_sname(sid) IS NULL
AND name NOT IN (‘dbo’, ‘guest’)

OPEN curSQL

FETCH curSQL INTO @sql

WHILE @@FETCH_STATUS = 0 BEGIN
EXEC (@sql)
PRINT @sql
FETCH curSQL INTO @sql
END

CLOSE curSQL
DEALLOCATE curSQL
GO

I hope this helps! Let us know if you have another way to sync database users to SQL Server logins.