How to check if user has permissions to see View definitions on SQL Server?

9q78igpj  于 2023-10-15  发布在  SQL Server
关注(0)|答案(3)|浏览(116)

How to find if the logged in User has permissions to see "view" definitions on SQL Server? I need to find out what tables/columns a view is made from,

I used this SQL for the same; for view definition, we used this query:

Query:

select * 
from sys.objects 
where name like '%SECTION_MASTER_V%'

Result: 579337674

Query:

SELECT definition
FROM sys.objects o
JOIN sys.sql_modules m ON m.object_id = o.object_id
WHERE o.object_id = 579337674
  AND o.type = 'V'

Result: null

I get null as a result. Does anyone knows what may be wrong here?

7vux5j2d

7vux5j2d1#

You can see object-level permissions using this query: the commented-out section in the WHERE clause will limit the results to the VIEW DEFINITION permission.

SELECT 
    o.name AS ObjectName,
    su.name AS LoginName,
    dp.permission_name AS PermissionType,
    dp.state_desc AS PermissionStatus
FROM 
    sys.database_permissions dp
     INNER JOIN 
    sys.objects o ON 
        dp.major_id = o.object_id
     INNER JOIN 
    sys.sysusers su ON 
        dp.grantee_principal_id = su.uid
--WHERE dp.[type] = 'vw'
ORDER BY o.name
5lwkijsr

5lwkijsr2#

I get null as a result. Does anyone knows what may be wrong here?

You need the VIEW DEFINITION permission, otherwise you get an empty result set.

Use can use sys.fn_my_permissions or HAS_PERMS_BY_NAME to get the relevant permission on a database for the current user:

HAS_PERMS_BY_NAME:
SELECT HAS_PERMS_BY_NAME(null, 'DATABASE', 'VIEW DEFINITION');

You get a simple 0 or 1 as a result of this query.

sys.fn_my_permissions
SELECT * FROM sys.fn_my_permissions(NULL, 'DATABASE') 
WHERE permission_name = N'VIEW DEFINITION'

The result set for this query looks like this:

entity_namesubentity_namepermission_name
databaseVIEW DEFINITION
With impersonation

If you have the IMPERSONATE permission, you can even check it for another user:

EXECUTE AS USER = 'otheruser'
SELECT HAS_PERMS_BY_NAME(null, 'DATABASE', 'VIEW DEFINITION');  
REVERT

or

EXECUTE AS USER = 'otheruser';
SELECT * FROM sys.fn_my_permissions(NULL, 'DATABASE')
WHERE permission_name = N'VIEW DEFINITION'
REVERT
wbgh16ku

wbgh16ku3#

Two things:

  1. Use sp_helptext: it's a lot easier than jumping through system tables.
  2. You can use sys.fn_my_permissions to see what permissions you have on any object.

相关问题