如何获取所有实例数据库上的用户列表?不包括镜子!

ano*_*002 4 sql-server ssms t-sql

为了审计我们的 MSSQL 数据库,我被要求提供每个实例上运行的每个数据库的所有用户的列表。

有一个现有的 s粘性溢出问题

建议使用...

exec sp_MSforeachdb 'select * from ?.sys.sysusers'
Run Code Online (Sandbox Code Playgroud)

但是,它遇到了一些问题。

1) 如果任何数据库是镜像,脚本会出现如下错误并且不返回任何结果。

"The database "###" cannot be opened. It is acting as a mirror database."
Run Code Online (Sandbox Code Playgroud)

2) 如果任何数据库的名称中包含特殊字符(例如连字符 -),则会再次出错并且不返回结果。

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '-'.
Run Code Online (Sandbox Code Playgroud)

3) 结果都在单独的表格中。理想情况下,我希望它只输出 1 个数据库和用户表。

任何人都可以帮助调整代码以实现上述目标吗?

谢谢

Dav*_*oft 8

sp_MSforeachdb没有记录,不受支持,并且有一些严重的缺点。你需要使用别的东西。要么将自己的光标写在 上sys.databases,如下所示:

declare c cursor local for
    select name 
    from sys.databases d
    where name not in ('master','model','tempdb') 
    and d.state=0
declare @db sysname

open c
fetch next from c into @db
while @@fetch_status = 0
begin
  begin try
     declare @sql nvarchar(max) = concat(  N'use ', quotename(@db), N'; 
     select db_name() db, * 
     from sys.database_principals u
     where type = ''U''' 
     )

     --print @sql
     exec ( @sql )

  end try
  begin catch
    print error_message()
  end catch

  fetch next from c into @db
end

close c
deallocate c
Run Code Online (Sandbox Code Playgroud)

或复制别人的,例如在这里