Get list of all database users with specified role

前端 未结 4 1545
情书的邮戳
情书的邮戳 2021-01-01 11:44

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

相关标签:
4条回答
  • 2021-01-01 11:58

    Something like this can help you:

            select sys.server_role_members.role_principal_id ,role.name  as rolename    
            , sys.server_role_members.member_principal_id , member.name as membername 
            from sys.server_role_members 
            join sys.server_principals as role
            on sys.server_role_members.role_principal_id = role.principal_id
            join sys.server_principals as member 
            on sys.server_role_members. member_principal_id = member_principal_id;
    
    0 讨论(0)
  • 2021-01-01 12:04

    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]
    
    0 讨论(0)
  • 2021-01-01 12:09

    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)
    
    0 讨论(0)
  • 2021-01-01 12:22

    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
    
    0 讨论(0)
提交回复
热议问题