In SQL Server 2005, how can I write a query to list all login, their server role, correspond user in all db, db role?

99封情书 提交于 2019-12-11 03:08:06

问题


I'm not clear about the security-related catalog views in SQL Server 2005 or 2008. I want to list all logins, their server roles, their correspond users in all database, all database roles in one query. How can I write the query?

I know there are some catalog views to use, but I'm not familiar with their relation. These catalog views include: sys.database_role_member, sys.database_principals, sys.server_role_member, sys.server_principals.

Thanks.


回答1:


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.




回答2:


Here is a query that will list all logins with their assigned server-level roles.

select 
  login_name = pa.name, 
  --pa.principal_id, m.member_principal_id, m.role_principal_id,pb.principal_id,
  role_name = pb.name
from
  sys.server_principals pa
  inner join
  sys.server_role_members m on pa.principal_id = m.member_principal_id
  inner join
  sys.server_principals pb on m.role_principal_id = pb.principal_id
order by
  pa.name,
  pa.principal_id


来源:https://stackoverflow.com/questions/3442575/in-sql-server-2005-how-can-i-write-a-query-to-list-all-login-their-server-role

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!