Created
June 30, 2015 19:55
-
-
Save jdavisclark/07d3155c5e121bda8f8b to your computer and use it in GitHub Desktop.
fix all orphaned users
This file contains hidden or 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
| SET NOCOUNT ON | |
| USE AdventureWorks | |
| GO | |
| DECLARE @loop INT | |
| DECLARE @USER sysname | |
| IF OBJECT_ID('tempdb..#Orphaned') IS NOT NULL | |
| BEGIN | |
| DROP TABLE #orphaned | |
| END | |
| CREATE TABLE #Orphaned (UserName sysname, UserSID VARBINARY(85),IDENT INT IDENTITY(1,1)) | |
| INSERT INTO #Orphaned | |
| EXEC SP_CHANGE_USERS_LOGIN 'report'; | |
| IF(SELECT COUNT(*) FROM #Orphaned) > 0 | |
| BEGIN | |
| SET @loop = 1 | |
| WHILE @loop <= (SELECT MAX(IDENT) FROM #Orphaned) | |
| BEGIN | |
| SET @USER = (SELECT UserName FROM #Orphaned WHERE IDENT = @loop) | |
| IF(SELECT COUNT(*) FROM sys.server_principals WHERE [Name] = @USER) <= 0 | |
| BEGIN | |
| EXEC SP_ADDLOGIN @USER,'password' | |
| END | |
| EXEC SP_CHANGE_USERS_LOGIN 'update_one',@USER,@USER | |
| PRINT @USER + ' link to DB user reset'; | |
| SET @loop = @loop + 1 | |
| END | |
| END | |
| SET NOCOUNT OFF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment