格兰特选择DMV导致错误

时间:2014-08-07 11:32:14

标签: sql sql-server

我需要向特定用户授予DM视图访问权限。

因此,我尝试在查询sys.dm_exec_query_stats的SP上授予VIEW DATABASE STATEVIEW SERVER STATE以及EXECUTE

它没有用,我试图在指定的DMV上授予SELECT

我收到错误'Cannot find the user <UserName>, because it does not exist or you do not have permission.' 下面脚本中的所有内容都可以与指定的用户一起使用,但最后一个语句是Grant Select。 任何猜测为什么?

Use MyDatabase
GRANT EXECUTE ON [MySchema].[SP_MySPROC] TO UserName
GRANT VIEW DATABASE STATE TO UserName

USE master;
GRANT VIEW SERVER STATE TO UserName
GRANT SELECT ON sys.dm_exec_query_stats TO UserName

1 个答案:

答案 0 :(得分:1)

指定的UserName必须是数据库主体(数据库用户),而不是服务器主体(登录)。我希望将用户显式添加到master数据库将解决GRANT问题,但您可以考虑使用提供所需权限的证书对proc进行签名。证书方法更复杂但更安全。以下是证书示例。

USE master;

-- create master database access certificate
CREATE CERTIFICATE MasterDatabaseUserCertificate
   ENCRYPTION BY PASSWORD = 'ksfd78#$%@8ks1@b@'
   WITH SUBJECT = 'Master database access certificate',
   START_DATE = '20020101', EXPIRY_DATE = '20990101';
GO

-- create the certificate login to assign server permissions
CREATE LOGIN MasterDatabaseUserCertificateLogin
    FROM CERTIFICATE MasterDatabaseUserCertificate;
GO

-- create the certificate user to assign database permissions
CREATE USER MasterDatabaseUserCertificateUser
    FOR LOGIN MasterDatabaseUserCertificateLogin;
GO

--grant server permissions
GRANT VIEW SERVER STATE TO MasterDatabaseUserCertificateLogin;
GO

--grant database permissions
GRANT SELECT ON sys.dm_exec_query_stats TO MasterDatabaseUserCertificateUser;
GO

--export certificate to file
BACKUP CERTIFICATE MasterDatabaseUserCertificate
    TO FILE = 'C:\temp\YourCertificate.cer'
    WITH PRIVATE KEY (FILE = 'C:\temp\MasterDatabaseUserCertificate.pvk' ,
        ENCRYPTION BY PASSWORD = 'ksfd78#$%@8ks1@b@',
        DECRYPTION BY PASSWORD = 'ksfd78#$%@8ks1@b@');
GO

USE MyDatabase;
GO

-- import the certificate from file
CREATE CERTIFICATE MasterDatabaseUserCertificate
    FROM FILE = 'C:\temp\YourCertificate.cer'
    WITH PRIVATE KEY (FILE = 'C:\temp\MasterDatabaseUserCertificate.pvk' ,
        ENCRYPTION BY PASSWORD = 'ksfd78#$%@8ks1@b@',
        DECRYPTION BY PASSWORD = 'ksfd78#$%@8ks1@b@');
GO

-- sign procedure with certificate
ADD SIGNATURE TO dbo.usp_MySPROC BY CERTIFICATE MasterDatabaseUserCertificate
    WITH PASSWORD = 'ksfd78#$%@8ks1@b@';
GO