declare @name varchar(150)
declare @query nvarchar (500)
DECLARE cur CURSOR FOR
select name from master..syslogins
Open cur
FETCH NEXT FROM cur into @name
WHILE @@FETCH_STATUS = 0
BEGIN
set @query='USE [?]
IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb''
BEGIN
exec sp_change_users_login ''Auto_Fix'', '''+ @name +'''
END'
EXEC master..sp_MSForeachdb @query
FETCH NEXT FROM cur into @name
END
CLOSE cur
DEALLOCATE cur
USE DBNAME ----- change db name for which you waant to fix orphan users issue
GO
declare @name varchar(150)
DECLARE cur CURSOR FOR
select name from master..syslogins
Open cur
FETCH NEXT FROM cur into @name
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC sp_change_users_login 'AUTO_FIX', @name
FETCH NEXT FROM cur into @name
END
CLOSE cur
DEALLOCATE cur
BEGIN
DECLARE @username varchar(25)
DECLARE fixusers CURSOR
FOR
SELECT UserName = name FROM sysusers
WHERE issqluser = 1 and (sid is not null and sid <> 0x0)
and suser_sname(sid) is null
ORDER BY name
OPEN fixusers
FETCH NEXT FROM fixusers
INTO @username
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC sp_change_users_login 'update_one', @username, @username
FETCH NEXT FROM fixusers
INTO @username
END
CLOSE fixusers
DEALLOCATE fixusers
END
go
Ted Krueger(推特上的@onpnt)写了一个很棒的脚本来做到这一点。它为没有登录名的任何用户添加登录名并运行 auto_fix。他甚至写了一篇文章,其中包括修复 Windows 登录:
http://blogs.lessthandot.com/index.php/DataMgmt/DBAdmin/fixing-orphaned-database-users
当然,如果您想先对其进行测试(或仅执行审计),您可以注释掉操作行 (
EXEC
),然后打印出结果。基于上述脚本,我们可以像这样使用 sp_MSForeachdb 修复实例中的所有用户
希望它会有所帮助
下面是完美完成这项工作的简单脚本——
这将是使用 dbatools 命令Repair-DbaDbOrphanUser的一个很好的用例
首先,您可以识别孤立用户
然后解决它们
为所有用户修复单个数据库的孤立用户