See:
https://www.mssqltips.com/sqlservertip/5999/sql-server-database-users-to-roles-mapping-report/
and
https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-server-role-members-transact-sql?view=sql-server-ver15#_examples
MS SQL server request to withdraw all users
Vladimir
21
Reputation points
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
Azure SQL Database
An Azure relational database service.
6,326 questions
Developer technologies Transact-SQL
4,707 questions
SQL Server Other
14,494 questions
7 answers
Sort by: Most helpful
-
-
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