更新时间:2023-02-07 11:12:24
您不能用一个查询列出所有数据库,因为该列表是动态的.您***的选择是使用 sp_msforeachdb
并批量构造结果并返回:
You cannot have one query list all databases because the list is dynamic. Your best bet is to use sp_msforeachdb
and have a batch construct the result and return it:
set nocount on;
create table #result (sid varbinary(85),
server_principal_id int,
database_id int,
database_principal_id int);
exec ms_foreachdb 'insert into #result
(server_principal_id, database_id, database_principal_id)
select s.principal_id,
db_id(''?''),
d.principal_id
from sys.server_principals s
join [?].sys.database_principals d
on s.sid = d.sid;';
select * from #result;
您可以将其扩展为包括服务器角色和数据库角色成员资格,一旦您找出合适的结果集形状,将所有信息聚合到一个表中.
You can extend this to include the server roles and database roles memberships once you figure out a proper result set shape to aggregate all that information in a single table.