Joseph Michael Pesch
VP Programming

Microsoft SQL Server TSQL Script to View All User Role Assignments

by 10. March 2015 04:01

 

/* The following will list all user role assignments in current database */


WITH RoleMembers (member_principal_id, role_principal_id)
AS
(
  SELECT
   rm1.member_principal_id,
   rm1.role_principal_id
  FROM sys.database_role_members rm1 (NOLOCK)
   UNION ALL
  SELECT
   d.member_principal_id,
   rm.role_principal_id
  FROM sys.database_role_members rm (NOLOCK)
   INNER JOIN RoleMembers AS d
   ON rm.member_principal_id = d.role_principal_id
)
select distinct rp.name as database_role, mp.name as database_user
from RoleMembers drm
  join sys.database_principals rp on (drm.role_principal_id = rp.principal_id)
  join sys.database_principals mp on (drm.member_principal_id = mp.principal_id)
order by rp.name

/* The following will list all user role assignments in all databases except master and tempdb */

create table #tmp(DatabaseName varchar(150), DatabaseRole varchar(150), DatabaseUser varchar(150))

declare @command varchar(max)

select @command = '
if ''?'' not in(''master'', ''tempdb'')
begin
    print ''?''
    use [?]
  ;
  WITH RoleMembers (member_principal_id, role_principal_id)
  AS
  (
    SELECT
     rm1.member_principal_id,
     rm1.role_principal_id
    FROM sys.database_role_members rm1 (NOLOCK)
     UNION ALL
    SELECT
     d.member_principal_id,
     rm.role_principal_id
    FROM sys.database_role_members rm (NOLOCK)
     INNER JOIN RoleMembers AS d
     ON rm.member_principal_id = d.role_principal_id
  )
  insert into #tmp select distinct ''?'', rp.name, mp.name
  from RoleMembers drm
    join sys.database_principals rp on (drm.role_principal_id = rp.principal_id)
    join sys.database_principals mp on (drm.member_principal_id = mp.principal_id)
  order by rp.name

end
'
exec sp_msforeachdb @command1 = @command

select * from #tmp

drop table #tmp

Tags:

SQL Server

Comments are closed