Listing Users and Their Roles in SQL Server

Hello everyone,

In this article, I will provide information about listing users and their roles in SQL Server.

In SQL Server, in some cases, we may want to list users and their roles.

You can easily do this with the help of the code below.

SELECT spU.name,
       MAX(   CASE
                  WHEN srm.role_principal_id = 3 THEN
                      1
              END
          ) AS sysadmin,
       MAX(   CASE
                  WHEN srm.role_principal_id = 4 THEN
                      1
              END
          ) AS securityadmin,
       MAX(   CASE
                  WHEN srm.role_principal_id = 5 THEN
                      1
              END
          ) AS serveradmin,
       MAX(   CASE
                  WHEN srm.role_principal_id = 6 THEN
                      1
              END
          ) AS setupadmin,
       MAX(   CASE
                  WHEN srm.role_principal_id = 7 THEN
                      1
              END
          ) AS processadmin,
       MAX(   CASE
                  WHEN srm.role_principal_id = 8 THEN
                      1
              END
          ) AS diskadmin,
       MAX(   CASE
                  WHEN srm.role_principal_id = 9 THEN
                      1
              END
          ) AS dbcreator,
       MAX(   CASE
                  WHEN srm.role_principal_id = 10 THEN
                      1
              END
          ) AS bulkadmin
FROM sys.server_principals AS spR
    JOIN sys.server_role_members AS srm
        ON spR.principal_id = srm.role_principal_id
    JOIN sys.server_principals AS spU
        ON srm.member_principal_id = spU.principal_id
WHERE spR.[type] = 'R'
GROUP BY spU.name;

When you run the code, you will get a result like the one below.

Listing Users and Their Roles in SQL Server

As you can see, all users and their roles are listed.

Good luck to everyone in business and life.

193 Views

Yavuz Selim Kart

I try to explain what I know in software and database. I am still improving myself by doing research on many programming languages. Apart from these, I am also interested in Graphic Design and Wordpress. I also have knowledge about SEO and Social media management. In short, I am a determined person who likes to work hard.

You may also like...

Don`t copy text!