Original Code obtained from here
http://community.spiceworks.com/scripts/show/819-find-and-fix-orphaned-users-in-sql-server
Modified slightly to work for SQL 2008 R2
/*
Disclaimer : As with all my code, if I didn't source someone else's work please bring it to my attention. I make all efforts
to make notes of where pieces of code came from to give someone credit for their hard work. However, there are times
that I miss something and I have no problem fixing that. Just give me the opportunity to attribute the source by letting
me know.
Type : Ad-Hoc
Name : n/a
Author : Jason Crider
Blog - http://www.jasoncrider.com/blog
Twitter - http://twitter.com/jasoncrider
LinkedIn - http://www.linkedin.com/pub/jason-crider/a/335/33
Email - arsqldba at gmail dot com
Purpose : Part 1 - Find Orphaned Users, Part 2 - Fix Orphaned Users
Notes : sp_change_users_login maps an existing database user to a SQL Server login. This feature will be removed in a future version of
Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that
currently use this feature. Use ALTER USER instead. (http://msdn.microsoft.com/en-us/library/ms174378%28v=SQL.105%29.aspx)
Syntax
sp_change_users_login [ @Action = ] 'action'
[ , [ @UserNamePattern = ] 'user' ]
[ , [ @LoginName = ] 'login' ]
[ , [ @Password = ] 'password' ]
Arguments
[@Action =] 'action'
(http://msdn.microsoft.com/en-us/library/aa259633%28v=sql.80%29.aspx)
*/
--Part 1 - Find orphaned users in current Database
Sp_change_users_login @Action='Report';
--Part 2 - Fix orphaned users in current Database
DECLARE @SQL VARCHAR(200)
DECLARE cursql CURSOR FOR
SELECT 'EXEC sp_change_users_login ''auto_fix'', '''
+ name + ''',NULL, ''' + name + ''''
FROM sysusers
WHERE issqluser = 1
AND name NOT IN ( 'guest', 'dbo', 'sys', 'INFORMATION_SCHEMA' )
OPEN cursql
FETCH cursql INTO @SQL
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC ( @SQL )
FETCH cursql INTO @SQL
END
CLOSE cursql
DEALLOCATE cursql
go
--Same as Part 1
--You can comment this part out, but it shows you that the orphaned users were actually fixed.
Sp_change_users_login @Action='Report'
No comments:
Post a Comment