Created
November 12, 2013 00:30
-
-
Save FembotDBA/7423212 to your computer and use it in GitHub Desktop.
Refresh orphaned users in a database after restore.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
IF EXISTS(SELECT * FROM tempdb..sysobjects WHERE id = object_id('tempdb..#t_users')) | |
drop table #t_users | |
CREATE TABLE #t_users ( [name] SYSNAME) | |
INSERT #t_users ( [name] ) | |
SELECT [name] | |
FROM sysusers | |
WHERE | |
islogin = 1 | |
AND name NOT IN ('dbo', 'public', 'guest', 'sys', 'INFORMATION_SCHEMA') | |
order by name | |
DECLARE @lc_name SYSNAME | |
SET @lc_name = (SELECT MIN([name]) FROM #t_users) | |
WHILE @lc_name IS NOT NULL | |
BEGIN | |
IF EXISTS(SELECT * FROM master..syslogins WHERE [name] = @lc_name) | |
BEGIN | |
EXEC sp_change_users_login 'AUTO_FIX', @lc_name | |
PRINT 'fixing ' + @lc_name | |
END | |
ELSE | |
PRINT '*** not fixing ' + @lc_name | |
SET @lc_name = (SELECT MIN([name]) FROM #t_users WHERE [name] > @lc_name ) | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment