Determining if a SQL Server table is read-only

后端 未结 3 1373
一个人的身影
一个人的身影 2021-01-26 02:55

What\'s the best way to determine if a given SQL Server table is read-only, either because of account permissions or the database being marked as read-only?

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-26 03:46

    --for database (updated for newer versions)
    SELECT DATABASEPROPERTYEX(DB_NAME(), 'Updateability')
    
    --for tables.
    SELECT
       *
    FROM
       sys.tables t
       LEFT JOIN
       sys.database_permissions dp2 ON dp2.major_id = t.object_id AND dp2.permission_name = 'SELECT'
    WHERE
       NOT EXISTS (SELECT * FROM 
             sys.database_permissions dp
          WHERE
             dp.major_id = t.object_id
             AND
             dp.permission_name IN ('INSERT', 'DELETE', 'UPDATE'))
    

    Modify * as needed to get what you want: this checks for none/SELECT where there is no I/U/D rights

    You also have FILEGROUPPROPERTY etc if you have read only filegroups

    Edit: for current connection and direct table rights per user. Does not iterate through group hierarchy

    SELECT
       *
    FROM
       sys.tables t
       JOIN
       sys.database_permissions dp2 ON dp2.major_id = t.object_id AND dp2.permission_name = 'SELECT'
    WHERE
       dp2.grantee_principal_id = USER_ID()
       AND
       dp.permission_name IN ('INSERT', 'DELETE', 'UPDATE'))
    

提交回复
热议问题