Archive for the 'Software Deployments' Category

SQL Database moved to another server – how to fix orphaned logins

Last night I was on support for a software deployment that saw one of our databases being moved from a legacy server to our main production SQL Server cluster.  Once we did, the SQL login we had created for our application to connect to the database was unable to access the db on the destination server, despite a SQL login of the same name and password having had access on the legacy server.

At first, I was surprised, as we had done this same type of move several times during testing, moving from my development machine to a QA SQL Server, and never experienced this issue.  Upon a few moment’s further thought, we were using a different SQL login in QA than in dev.  So after moving the database from dev to QA, we had a step to update the user mapping to give it access to the database.  I didn’t think this was necessary on the production move, since the login already existed on both servers, and had access to the database on the legacy server.

Then I remembered that in the past we had experienced orphaning of some logins when moving databases between servers.  I couldn’t remember the resolution of how to resolve it, so I set out to Google and quickly found an answer I liked, on this thread:  http://dba.stackexchange.com/questions/40844/after-moving-database-backup-restore-i-have-to-re-add-user

I’ve decided to capture it here for prosperity.

First step is diagnosis–you can run this query to check for any orphaned logins in your database:

use [Your Database Name Here]
go

select
    dp.name [user_name]
    ,dp.type_desc [user_type]
    ,isnull(sp.name,'Orhphaned!') [login_name]
    ,sp.type_desc [login_type]
from   
    sys.database_principals dp
    left join sys.server_principals sp on (dp.sid = sp.sid)
where
    dp.type in ('S','U','G')
    and dp.principal_id >4
order by sp.name

Yes, the above query is a direct copy and paste from the article I linked.  I just wanted to have it on my own blog for easy accessibility in the future.  Full credit to Mike Fal, the first responder on that thread.

Once you’ve confirmed that the login you’re interested in displays “Orphaned!” (and yes, ours did), a very simple fix exists:

ALTER USER [LoginNameHere] WITH LOGIN=[LoginNameHere]

This re-associates the database user LoginNameHere, with the server login LoginNameHere.  After we did this step, all was good.

Advertisements

Scott’s recent tweets…