Created
August 22, 2024 10:37
-
-
Save nanoDBA/f58dac485750704bc36aab842506bc97 to your computer and use it in GitHub Desktop.
Retrieve securables and permissions for any specified database role. Uses a variable for the role name and prompts the user if the role name is not provided. Modeled after SSMS Securables page of Database Roles properties
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- database_role_securables_query.sql | |
-- modeled after SSMS Securables page of Database Roles properties | |
DECLARE @RoleName NVARCHAR(128); | |
SET @RoleName = ''; -- Replace with role name or leave empty for testing | |
IF @RoleName = '' | |
BEGIN | |
SELECT 'Please provide a valid role name to query securables' AS Message; | |
END | |
ELSE | |
BEGIN | |
SELECT dp.name AS DatabaseRole, | |
rm.name AS RoleMember, | |
CASE | |
WHEN o.type_desc = 'SCHEMA' THEN '' -- Leave Schema blank when Type is 'Schema' | |
ELSE s.name | |
END AS SchemaName, | |
CASE | |
WHEN o.type_desc = 'SCHEMA' THEN s.name -- Use Schema name as the Name when Type is 'Schema' | |
WHEN m.name IS NOT NULL THEN m.name -- Show schema name for schema-level permissions | |
ELSE o.name | |
END AS Name, | |
CASE | |
WHEN o.type_desc IS NOT NULL THEN o.type_desc | |
WHEN m.name IS NOT NULL THEN 'SCHEMA' -- Ensure 'SCHEMA' is shown for schema-level permissions | |
ELSE 'DATABASE' | |
END AS Type, | |
p.permission_name AS PermissionType, | |
p.state_desc AS PermissionState, | |
pr.name AS Grantor | |
FROM sys.database_principals dp WITH (NOLOCK) | |
INNER JOIN sys.database_role_members drm WITH (NOLOCK) ON dp.principal_id = drm.role_principal_id | |
INNER JOIN sys.database_principals rm WITH (NOLOCK) ON drm.member_principal_id = rm.principal_id | |
LEFT JOIN sys.database_permissions p WITH (NOLOCK) ON dp.principal_id = p.grantee_principal_id | |
LEFT JOIN sys.objects o WITH (NOLOCK) ON p.major_id = o.object_id | |
LEFT JOIN sys.schemas s WITH (NOLOCK) ON o.schema_id = s.schema_id | |
LEFT JOIN sys.database_principals pr WITH (NOLOCK) ON p.grantor_principal_id = pr.principal_id | |
LEFT JOIN sys.schemas m WITH (NOLOCK) ON p.major_id = m.schema_id AND o.name IS NULL -- For schema-level permissions | |
WHERE dp.name = @RoleName --role name goes here | |
ORDER BY RoleMember, | |
Type, | |
SchemaName, | |
Name, | |
PermissionType | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment