If a dump of a SQL Server user database is restored to a different SQL Server (such as a hot backup server) or...
By submitting your personal information, you agree that TechTarget and its partners may contact you regarding relevant content, products and special offers.
to the same SQL Server after either rebuilding or reloading an old version of the master database, user logons and permissions on the database may be incorrect. This will also occur if the database is detached and attached to a different (or even the same) server.
The DBA will usually get this error:
Microsoft SQL-DMO (ODBC SQLState: 42000) Error 15023: User or role '%s' already exists in the current database.
This info can be found buried deep within TechNet, but I have seen this error posted on several boards so I thought it might be helpful. Here is a script that will fix a single user where login = username:
EXEC sp_change_users_login 'Auto_Fix', 'login' --This will loop through the master db --and fix all users within a database. --this example fixes users within the --model db but could be modified for --any database DECLARE logins CURSOR KEYSET FOR SELECT name FROM master..sysusers WHERE islogin = '1' ORDER BY 'uid' DECLARE @login sysname OPEN logins FETCH NEXT FROM logins INTO @login WHILE (@@FETCH_STATUS=0) BEGIN EXEC model..sp_change_users_login 'auto_fix', @login FETCH NEXT FROM logins INTO @login END --PRINT @@CURSOR_ROWS CLOSE logins DEALLOCATE logins
For More Information
- What do you think about this tip? E-mail us at editor@searchDatabase.com with your feedback.
- The Best SQL Server Web Links: tips, tutorials, scripts, and more.
- Have an SQL Server tip to offer your fellow DBA's and developers? The best tips submitted will receive a cool prize--submit your tip today!
- Ask your technical SQL Server questions--or help out your peers by answering them--in our live discussion forums.
- Check out our Ask the Experts feature: Our SQL, Database Design, Oracle, SQL Server, and DB2 gurus are waiting to answer your toughest questions.