Question : SQL 2005 refreshing database users

I am refreshing databases from one environment to another. I need a script that will generate all users from the old db and create a script to generate the users on the new db, some of the user may be in the new database. also if it it could add the user to it's old db role, that would be great.
if exist (select * from sys.database_principles wher name = 'user')
  exec sp_change_user_logins 'auto_fix','user'
else
  create 'user' for 'login 'user'

Answer : SQL 2005 refreshing database users

-- try
-- from  http://social.msdn.microsoft.com/forums/en-US/sqlsecurity/thread/4a45a56c-31b4-4396-93fb-f46a881bdb7f/

--also check http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=12615
--create logins manually (in case of sql logins you need to type password for each user in "create login " -> it is unsecure
-----------------------------------------------------------------
sp_change_users_login @action = 'report'
go

-- Generate list of orphaned users
SELECT
Row_Number() OVER(ORDER BY [m].[name]) AS [id], [m].[name]
INTO [#temptbl]
FROM [sysusers] [loc] Inner Join [sys].[server_principals] [m] ON [loc].[name] = [m].[name]
WHERE [loc].[sid] <> [m].[sid] And [type] IN ('S','U')

DECLARE @liI INT,
       @liMax INT,
       @lcUserName NVARCHAR(256)

SELECT @liI =Min([id]), @liMax = Max([id]) FROM [#temptbl]

-- iterate through list of orphaned users and fix
WHILE @liI <= @liMax
BEGIN
   SELECT @lcUserName = [name] FROM [#temptbl] WHERE [id] = @liI
   EXEC ('ALTER USER ' + @lcUserName + ' WITH LOGIN = ' + @lcUserName)
   SET @liI = @liI + 1
END
DROP TABLE [#temptbl]
GO

sp_change_users_login @Action='Report';
GO

Random Solutions  
 
programming4us programming4us