To include the user’s role(s) in the output when querying which databases a particular user exists in, you can modify the query to gather both the users and their associated roles from the sys.database_role_members view. Here’s how you can do it, both for a single database and for a script that checks across all databases.
Single Database Query
If you want to check for a specific database, you can use the following query:
DECLARE @DatabaseName NVARCHAR(255) = 'YourDatabaseName'; -- Replace with your database name
DECLARE @UserName NVARCHAR(100) = 'YourUserName'; -- Replace with user name you want to check
USE [YourDatabaseName]; -- Switch to your specific database
SELECT
p.name AS UserName,
r.name AS RoleName
FROM
sys.database_principals p
LEFT JOIN
sys.database_role_members m ON p.principal_id = m.member_principal_id
LEFT JOIN
sys.database_principals r ON m.role_principal_id = r.principal_id
WHERE
p.name = @UserName
AND p.type IN ('S', 'U'); -- S for SQL user, U for Windows user
Across All Databases
If you want to check across multiple databases and include the roles for each database, you can modify the cursor script as follows:
DECLARE @DatabaseName NVARCHAR(255)
DECLARE @SQL NVARCHAR(MAX)
DECLARE @UserName NVARCHAR(100) = 'YourUserName'; -- Replace with the user name you want to check
DECLARE db_cursor CURSOR FOR
SELECT name
FROM sys.databases
WHERE state_desc = 'ONLINE';
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @DatabaseName;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = '
USE [' + @DatabaseName + '];
IF EXISTS (SELECT 1 FROM sys.database_principals WHERE name = ''' + @UserName + ''')
BEGIN
SELECT
''' + @DatabaseName + ''' AS DatabaseName,
p.name AS UserName,
r.name AS RoleName
FROM
sys.database_principals p
LEFT JOIN
sys.database_role_members m ON p.principal_id = m.member_principal_id
LEFT JOIN
sys.database_principals r ON m.role_principal_id = r.principal_id
WHERE
p.name = ''' + @UserName + '''
AND p.type IN (''S'', ''U'');
END'
EXEC sp_executesql @SQL;
FETCH NEXT FROM db_cursor INTO @DatabaseName;
END
CLOSE db_cursor;
DEALLOCATE db_cursor;
Explanation of Key Sections:
-
JOINs Explained:
sys.database_principals contains information about users and roles.
sys.database_role_members maps users to their respective roles.
- The left joins allow us to fetch the role name along with the username.
-
Dynamic SQL:
- The script builds a dynamic SQL string to switch databases and check for the user and their roles.
-
Results:
- The output will show the database name, user name, and their corresponding role(s) for each database where the user exists.
This way, you'll not only see which databases a particular user exists in but also the roles they belong to in those databases.