David Truxall

Adrift in .Net

<October 2008>
SuMoTuWeThFrSa
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678


Navigation

Other Good Blogs

My Other Articles on CodeProject

Subscriptions

News

Day of .Net October 18, 2008 - Be there!
View David Truxall's profile on LinkedIn
My presentations on SlideShare

Post Categories



Sql Server Fix Logins

Sometimes when copying databases, for instance from production down to development, the user accounts become dysfunctional. The database login no longer matches the overall server login. To re-synchronize them use:

exec sp_change_users_login auto_fix, 'someusername'

posted on Tuesday, June 05, 2007 3:12 PM by davetrux


# re: Sql Server Fix Logins @ Wednesday, June 06, 2007 4:43 PM

Yeah, it's quite a pain to move/synch accounts between servers. In case you don't know, sp_change_users_login does not truly "synchronize" the logins and users between development and production (or between primary and standby in a DR scenario).

How sp_change_users_login is that it runs a CREATE LOGIN statement to create the new login (if you use ATUO_FIX, for example) and then it remaps the database user account to the new login. That is NOT synchronizing the logins. Why?

Well, when sp_change_users_login ran CREATE LOGIN, it created a login with a completely new, random SID. If you need to now backup the development database and restore it on the production server again (probably more likely in a DR scenario) then you've got to do this whole process all over again :(

I suggest you only use sp_change_users_login in one-way transfers that will neve be updated/restored-on-top-of again from the original server. sp_change_users_login is fine when you want to take a copy of production, move it to QA, and then throw it away (i.e., delete the QA database and never restore a production copy over it again).

For anyone who has to repeatedly take backups from ServerA and restore them to ServerB, I suggest you look to sp_help_rev_logins which is a proc from MSFT PSS designed to keep servers in sync. Search the MSFT KBs for it...

Scott Whigham

# re: Sql Server Fix Logins @ Thursday, June 07, 2007 2:33 PM

Alternatively, to fix all orphaned users in the current database:

DECLARE @UserName sysname
DECLARE OrphanedUsers CURSOR LOCAL FAST_FORWARD
FOR
SELECT
[Name]
FROM
dbo.sysusers
WHERE
IsSqlUser = 1
And
Sid Is Not Null
And
0x0 <> Sid
And
SUser_SName(sid) Is Null
ORDER BY
[Name]

OPEN OrphanedUsers
FETCH NEXT FROM OrphanedUsers INTO @UserName
WHILE 0 = @@Fetch_Status
BEGIN
PRINT 'Orphaned user: ' + @UserName
EXEC sp_change_users_login 'UPDATE_ONE', @UserName, @UserName
FETCH NEXT FROM OrphanedUsers INTO @UserName
END

CLOSE OrphanedUsers
DEALLOCATE OrphanedUsers

Richard




Powered by Dot Net Junkies, by Telligent Systems