Sql server按名称获取数据库权限

时间:2016-10-31 09:39:01

标签: sql-server

我们可以在特定数据库中通过sp_helprotect获取权限。然后,如何获取特定数据库的权限,例如mastertempdb

我已经通过mysel尝试了这个声明:

SELECT major_id, minor_id, grantor_principal_id, grantee_principal_id, permission_name, pr1.name as GRANTEE, pr2.name as GRANTOR, pr2.create_date, pr2.modify_date 
    FROM (SELECT * FROM sys.database_permissions where class = 4) as pe
JOIN sys.database_principals AS pr1
    ON pe.grantee_principal_id = pr1.principal_id
JOIN sys.database_principals AS pr2
    ON pe.grantor_principal_id = pr2.principal_id

但是主要ID是0,所以我无法获得对哪个对象的许可。

1 个答案:

答案 0 :(得分:0)

sys.database_permissions的{​​{3}}声明:

  

为数据库中的每个权限或列异常权限返回一行。对于列,每个权限都有一行与相应的对象级权限不同。如果列权限与相应的对象权限相同,则不会有任何行,并且所使用的实际权限将是该对象的权限。

所以这意味着您的查询将仅返回运行它的数据库的上下文的权限。您目前正在做的是使用数据库主体(查询的class = 4部分)上存在的权限进行过滤。如果您需要数据库对象(例如表,存储过程等),则还应在类WHERE子句中包含1。

编辑1:要获取tempdb或master的权限,您可以使用以下命令运行查询两次:

USE master;
GO
/* Your query here that will return the permissions for master */
USE tempdb;
GO
/* Your query here that will return the permissions for master */

编辑2:如果您想要一个查询,可以使用这个:

SELECT major_id, minor_id, grantor_principal_id, grantee_principal_id,   permission_name, pr1.name as GRANTEE, pr2.name as GRANTOR, pr2.create_date, pr2.modify_date , 'master' as db
FROM 
(SELECT * FROM master.sys.database_permissions where class = 4) as pe
INNER JOIN master.sys.database_principals AS pr1
   ON pe.grantee_principal_id = pr1.principal_id
INNER JOIN master.sys.database_principals AS pr2
   ON pe.grantor_principal_id = pr2.principal_id
UNION ALL 
SELECT major_id, minor_id, grantor_principal_id, grantee_principal_id, permission_name, pr1.name as GRANTEE, pr2.name as GRANTOR, pr2.create_date, pr2.modify_date , 'tempdb' as db
FROM 
(SELECT * FROM tempdb.sys.database_permissions where class = 4) as pe
INNER JOIN tempdb.sys.database_principals AS pr1
   ON pe.grantee_principal_id = pr1.principal_id
INNER JOIN tempdb.sys.database_principals AS pr2
   ON pe.grantor_principal_id = pr2.principal_id;