Update Orphaned SQL Users
SQL Script to relink orphaned users to logins
When you move a database from one server that is running SQL Server to another server that is running SQL Server, a mismatch may occur between the security identification numbers (SIDs) of the logins in the master database and the users in the user database. By default, SQL Server 7.0, SQL Server 2000, and SQL Server 2005 provide the sp_change_users_login system stored procedure to map these mismatched users. However, you can only use the sp_change_users_login stored procedure to map standard SQL Server logins and you must perform these mapping for one user at a time.
Therefore the issue becomes how to sync up the logins in the copied database that relate to Login SID's that no longer exist on the server. If you try to manually re-save the login and grant it access to the copied database you are likely to run into problems with an error that prevents you from accomplishing the task such as:
-- example output to relink logins to users
USE myDB1
GO
EXEC sp_change_users_login 'UPDATE_ONE', 'mydatabase101', 'mydatabase101'
GO
USE myDB2
GO
EXEC sp_change_users_login 'UPDATE_ONE', 'mydatabase_admin_101', 'mydatabase_admin_101'
GO
IF @MODE = 'SQL'
BEGIN
-- loop each orphan and generate auto fix code
SELECT @MaxRow = COUNT(*), @RowID = 0
FROM #RESULTS
IF @MaxRow > 0
BEGIN
WHILE @RowID > @MaxRow
BEGIN
SELECT @RowID = @RowID + 1
SELECT @DatabaseName = DatabaseName
,@OrphanedUser = OrphanedUser
FROM #RESULTS
WHERE RowID = @RowID
-- output the TSQL to relink the user with the login
SELECT @SQL = 'USE ' + @DatabaseName + + CHAR(13) + CHAR(10)
+'GO' + CHAR(13) + CHAR(10)
+'EXEC sp_change_users_login ''UPDATE_ONE'', ''' + @OrphanedUser + ''', ''' + @OrphanedUser + '''' + CHAR(13) + CHAR(10)
+'GO' + CHAR(13) + CHAR(10)
PRINT @SQL
END
END
END
ELSE -- output the orphans
BEGIN
SELECT *
FROM #Results
ORDER BY [DatabaseName], [OrphanedUser]
ENDLabels: Backup, Database, Logins, Restore, SID, SQL Server, Users



1 Comments:
I have also found an interesting script to re-link Orphaned users this script uses a stored procedure.
USE MyDatabaseName
DECLARE @login nvarchar(50)
DECLARE logins_cursor CURSOR FOR SELECT l.name FROM sys.database_principals u INNER JOIN sys.server_principals l ON u.sid=l.sid
OPEN logins_cursor FETCH NEXT FROM logins_cursor INTO @login
WHILE @@FETCH_STATUS = 0 BEGIN EXEC sp_help_revlogin @login FETCH NEXT FROM logins_cursor INTO @login END
CLOSE logins_cursor DEALLOCATE logins_cursor
GO
Here is the url where you can also find a script from Microsoft to generate the T-SQL script to recreate a login.
http://www.sqlserveroptimizer.com/2011/08/how-to-script-logins-from-user-database-in-sql-server-20052008-r2/
Post a Comment
Subscribe to Post Comments [Atom]
Links to this post:
Create a Link
<< Home