HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Verify if user has read access to a table

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
readtableuserverifyhasaccess

Problem

I'm developing an ETL, which must read data from a table.

There are times that my user's access to that table is revoked. So, to avoid the ETL failing, before reading the table I must verify if I have permission to do it. If not, I'll just skip the extract step and run the rest of the ETL.

What's the proper way of verifying if my user has read permission over a table?

Solution

To check for a specific effective permission on a securable, use HAS_PERMS_BY_NAME*.

For example, to show if the current security context has SELECT permission on the Production.Product table in the AdventureWorks sample database:

SELECT 
    HAS_PERMS_BY_NAME
    (
        N'Production.Product', 
        N'OBJECT', 
        N'SELECT'
    );


Related: To list effective permissions on a securable, use sys.fn_my_permissions:

SELECT
    P.[entity_name],
    P.subentity_name,
    P.[permission_name]
FROM sys.fn_my_permissions
    (
        N'Production.Product', 
        N'OBJECT'
    ) AS P
ORDER BY
    P.subentity_name,
    P.[permission_name];


* The built-in function takes everything into account. SQL Server has to know how to correctly determine effective permissions. This function exposes that ability.

Code Snippets

SELECT 
    HAS_PERMS_BY_NAME
    (
        N'Production.Product', 
        N'OBJECT', 
        N'SELECT'
    );
SELECT
    P.[entity_name],
    P.subentity_name,
    P.[permission_name]
FROM sys.fn_my_permissions
    (
        N'Production.Product', 
        N'OBJECT'
    ) AS P
ORDER BY
    P.subentity_name,
    P.[permission_name];

Context

StackExchange Database Administrators Q#83474, answer score: 9

Revisions (0)

No revisions yet.