How can I view all grants for an SQL Database?

前端 未结 5 933
无人共我
无人共我 2020-12-31 00:49

I am using SQL Server 2005, I want to find out what all the grants are on a specific database for all tables. It would also help to find out all tables where the delete gran

5条回答
  •  情歌与酒
    2020-12-31 01:43

    I liked the answer from K. Brian Kelly but I wanted a little more information (like the schema) as well as generating the corresponding GRANT and REVOKE statements so I could apply them in different environments (e.g. dev/test/prod).

    note you can easily exclude system objects, see commented where clause

    select 
        class_desc 
        ,USER_NAME(grantee_principal_id) as user_or_role
        ,CASE WHEN class = 0 THEN DB_NAME()
              WHEN class = 1 THEN ISNULL(SCHEMA_NAME(o.uid)+'.','')+OBJECT_NAME(major_id)
              WHEN class = 3 THEN SCHEMA_NAME(major_id) END [Securable]
        ,permission_name
        ,state_desc
        ,'revoke ' + permission_name + ' on ' +
            isnull(schema_name(o.uid)+'.','')+OBJECT_NAME(major_id)+ ' from [' +
            USER_NAME(grantee_principal_id) + ']' as 'revokeStatement'
        ,'grant ' + permission_name + ' on ' +
            isnull(schema_name(o.uid)+'.','')+OBJECT_NAME(major_id)+ ' to ' +
            '[' + USER_NAME(grantee_principal_id) + ']' as 'grantStatement'
    FROM sys.database_permissions dp
    LEFT OUTER JOIN sysobjects o
        ON o.id = dp.major_id
    -- where major_id >= 1  -- ignore sysobjects
    
    order by 
        class_desc desc
        ,USER_NAME(grantee_principal_id)
        ,CASE WHEN class = 0 THEN DB_NAME()
             WHEN class = 1 THEN isnull(schema_name(o.uid)+'.','')+OBJECT_NAME(major_id)
             WHEN class = 3 THEN SCHEMA_NAME(major_id) end
        ,permission_name
    

提交回复
热议问题