MS SQL server request to withdraw all users

Vladimir 21 Reputation points
2022-01-22T10:15:53.377+00:00

Hello everyone!
Please help me make a request in MS SQL Server
It is necessary to display all accounts, sql and domain, which will display the fields account name, conestion string, database name, Usermapingdatabase (screenshot 2) and server role (screenshot 3)
an example of how it should look for one account (screenshot1)

Azure SQL Database
Developer technologies Transact-SQL
SQL Server Other
{count} votes

7 answers

Sort by: Most helpful
  1. Tom Phillips 17,771 Reputation points
    2022-01-31T13:50:08.88+00:00

  2. Vladimir 21 Reputation points
    2022-02-01T07:48:16.917+00:00

    It turned out to be done like this:

    select DB_NAME() as db, u.name as [login], r.name as [role], u.[sid] 
    into ##db_users_roles01
    from
    sys.database_principals u
    left join sys.database_role_members m on u.principal_id = m.member_principal_id
    left join sys.database_principals r on r.principal_id = m.role_principal_id
    where u.type in ('S', 'U') and 1=2
    exec sp_msforeachdb 'use [?]; 
    insert into ##db_users_roles01
    select DB_NAME() as db, u.name as [login], r.name as [role], u.[sid] from
    sys.database_principals u
    left join sys.database_role_members m on u.principal_id = m.member_principal_id
    left join sys.database_principals r on r.principal_id = m.role_principal_id
    where u.type in (''S'', ''U'')'
    select *, 1 as [public] from (
    select sp.name as serverLoginName, Isnull(srp.name,'public') as ServerRoleName,db,role,1 as value
    From sys.server_principals  sp
    left join sys.server_role_members srm on sp.principal_id = srm.member_principal_id 
    left join sys.server_principals srp on srp.principal_id = srm.role_principal_id
    left join ##db_users_roles01 dbr on dbr.sid = sp.sid
    where sp.type in ('S', 'U')
    )sub
    Pivot( Sum(value) for role in (
    db_accessadmin      ,
    db_backupoperator    ,
    db_datareader      ,
    db_datawriter      ,
    db_ddladmin        ,
    db_denydatareader    ,
    db_denydatawriter    ,
    db_owner             ,
    db_securityadmin     ,
    SCOM_HealthService
    )) as piv
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.