Login or Sign Up to become a member!
LessThanDot Site Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

Fix Orphaned Database Users

From Wiki

Jump to: navigation, search

Most common when performing restores or re-attaching databases, database users become orphaned. This simply means the database user is not assocaited with a sql server login. To fix these situations you can run the following in the database context that the database user exists in


  1. SET NOCOUNT ON
  2. USE AdventureWorks
  3. GO
  4. DECLARE @loop INT
  5. DECLARE @User sysname
  6.  
  7. IF OBJECT_ID('tempdb..#Orphaned') IS NOT NULL
  8.  BEGIN
  9.   DROP TABLE #orphaned
  10.  END
  11.  
  12. CREATE TABLE #Orphaned (UserName sysname, UserSID varbinary(85),IDENT INT IDENTITY(1,1))
  13.  
  14. INSERT INTO #Orphaned
  15. EXEC sp_change_users_login 'report';
  16.  
  17. IF(SELECT COUNT(*) FROM #Orphaned) > 0
  18. BEGIN
  19.  SET @loop = 1
  20.  WHILE @loop <= (SELECT MAX(IDENT) FROM #Orphaned)
  21.   BEGIN
  22.     SET @user = (SELECT UserName FROM #Orphaned WHERE IDENT = @loop)
  23.     IF(SELECT COUNT(*) FROM sys.server_principals WHERE [Name] = @User) <= 0
  24.      BEGIN
  25.         EXEC sp_addlogin @User,'password'
  26.      END
  27.      
  28.     EXEC sp_change_users_login 'update_one',@User,@User
  29.     PRINT @user + ' link to DB user reset';
  30.     SET @loop = @loop + 1
  31.   END
  32. END
  33. SET NOCOUNT OFF

--onpnt 01:31, 14 April 2010 (GMT)

659 Rating: 2.4/5 (77 votes cast)