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.
Fix Orphaned Database Users
From Wiki
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
- 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
--onpnt 01:31, 14 April 2010 (GMT)



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