Tuesday 18 August 2015

SQL Server Orphaned User Issue

Orphaned Users are created, When a database is moved (Restore or detach/attach) from one server to another server the login SID's stored in the master database don't match/mapped with the login SID's stored in the user database.
Follow below steps to remove orphan users:

To get the report of Orphaned Users
To detect orphaned users, execute the following T-SQL statement:

USE DB_name
GO 
Exec sp_change_users_login 'Report'
GO
Note: sp_change_users_login cannot be used with SQL Server logins that are created from Windows.

To view difference in SID of Orphaned User
USE master
GO 
SELECT name as SQLServerLogin,SID as SQLServerSID FROM sys.syslogins
WHERE [name] = 'User_name'
GO

USE DB_Name
GO 
SELECT name DatabaseID,SID as DatabaseSID FROM sysusers
WHERE [name] = 'User_Name'
GO
The result of above query will shows that the SID of the SQL Server login and that of the user database SID differ and that's the cause of the problem.

To Resolve an Orphaned User
To resolve an orphaned user, use the following procedure:
1. Command to Auto map:
EXEC sp_change_users_login 'Auto_Fix', 'User_name';
GO
2. Command to create and map an orphaned user to a login
EXEC sp_change_users_login 'Auto_Fix', 'User_Name', null,'password';
GO

Script to script out T-SQL commands to auto fix all SQL Logins
Execute below command in 'Result to text' Mode
IF OBJECT_ID('tempdb..#Orphaned') IS NOT NULL 
 BEGIN
  Drop TABLE #orphaned
 END
Create TABLE #Orphaned (UserName sysname, UserSID VARBINARY(85))
Exec sp_MSforeachdb 'USE [?] ; INSERT INTO #Orphaned Exec sp_change_users_login ''Report'' ;
Select ''USE ['' + DB_name() + '']; '' 
+ ''EXEC sp_change_users_login ''''Auto_Fix'''','' + '''' 
+ [username] + '''' from tempdb..#Orphaned; Truncate TABLE #orphaned'


No comments:

Post a Comment