tags:

views:

37

answers:

3

I want to get list of all database users with specified role. Role is a parameter for stored procedure or function.

Somethinf like a select statement with user name and its role.

+============+==========
| User name  |  Role   |
+============+==========

MS SQL Server 2008

A: 

Probably use something like this

SELECT
    SU.Name AS UserName, SR.Name AS RoleName
FROM
    sysUsers AS SU
      INNER JOIN 
     sysUsers AS SR ON SU.GID = SR.UID
WHERE
    SU.GID <> SU.UID
ORDER BY
  RoleName, UserName

Borrowed from SmartBihari's Blog

EDIT 1 To Get the System Roles associated with a user. The sys.sysmembers is a system view which has the memberuid and the groupuid as the only columns. you can use the user_name() function to retreive the name of each column.

USE [YourDatabase]
SELECT user_name([memberuid]) as [Username], User_Name([groupuid]) as [Role_Name]
FROM [sys].[sysmembers]
Nathan Fisher
it's not returned role names of users.
nik
sys.sysmembers is from SQL-Server 2000. 2005/2008 are backward compatible, so no problem (yet), but if you're just learning how to do this in 2008, then I'd recommend using sys.database_role_members instead.
dave
cool. Thanks Dave
Nathan Fisher
A: 

just depending on how you want to pass the parameter...assuming you'll use the id of the role

declare @roleID int

select
    role_principal_id as roleID, 
    user_name(role_principal_id) as roleName, 
    member_principal_id as memberID,
    user_name(member_principal_id) as memberName 
from 
    sys.database_role_members
where 
    role_principal_id = @roleID
dave
+1  A: 

In SQL 2005 and 2008 this information is most easily accessed in two catalog views.

This query should give you the information you're looking for.

select rp.name as database_role, mp.name as database_user
from sys.database_role_members 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)
Jim V.