我正在M SQL Server 2017中使用tsql。如何查看用户定义的数据库角色具有哪些权限?
例如,我有一个数据库,该数据库的用户定义角色在数据库“ abc”中称为“ ViewDefinitions”。
我想编写一个查询,使我可以查看此角色具有哪些特定权限。
答案 0 :(得分:0)
这可能需要一些清理工作,但这是我为此目的保留的临时脚本。
DECLARE @rolename VARCHAR(100) = 'testrole'
SELECT * FROM (
--database level permissions
SELECT
'Database' AS [permissionLevel]
,CASE WHEN perm.state <> 'W' THEN perm.state_desc ELSE 'GRANT' END
+ SPACE(1) + perm.permission_name + SPACE(1)
+ SPACE(1) + 'TO' + SPACE(1) + usr.name COLLATE database_default
+ CASE WHEN perm.state <> 'W' THEN SPACE(0) ELSE SPACE(1) + 'WITH GRANT OPTION' END AS [rolePermisison]
,perm.permission_name
,perm.state_desc
FROM sys.database_permissions AS perm
INNER JOIN
sys.database_principals AS usr
ON perm.grantee_principal_id = usr.principal_id
WHERE usr.name = @rolename
AND perm.major_id = 0
UNION all
--object level permissions
SELECT
'Object' AS [permissionLevel]
,CASE WHEN perm.state <> 'W' THEN perm.state_desc ELSE 'GRANT' END
+ SPACE(1) + perm.permission_name + SPACE(1) + 'ON ' + QUOTENAME(SCHEMA_NAME(obj.schema_id)) + '.' + QUOTENAME(obj.name)
+ CASE WHEN cl.column_id IS NULL THEN SPACE(0) ELSE '(' + QUOTENAME(cl.name) + ')' END
+ SPACE(1) + 'TO' + SPACE(1) + QUOTENAME(usr.name) COLLATE database_default
+ CASE WHEN perm.state <> 'W' THEN SPACE(0) ELSE SPACE(1) + 'WITH GRANT OPTION' END
,perm.permission_name
,perm.state_desc
FROM sys.database_permissions AS perm
INNER JOIN
sys.objects AS obj
ON perm.major_id = obj.[object_id]
INNER JOIN
sys.database_principals AS usr
ON perm.grantee_principal_id = usr.principal_id
LEFT JOIN
sys.columns AS cl
ON cl.column_id = perm.minor_id AND cl.[object_id] = perm.major_id
WHERE usr.name = @rolename
) A
ORDER BY permissionLevel, permission_name ASC, state_desc ASC