Scripting SQL Server permissions

前端 未结 9 1948
轮回少年
轮回少年 2021-01-30 02:58

I want to copy all the permission I\'ve set on stored procedures and other stuff from my development database to my production database. It\'s incredibly cumbersome, not to ment

9条回答
  •  清酒与你
    2021-01-30 03:53

    The database's built-in catalog views provide the information to do this. Try this query:

    SELECT
      (
        dp.state_desc + ' ' +
        dp.permission_name collate latin1_general_cs_as + 
        ' ON ' + '[' + s.name + ']' + '.' + '[' + o.name + ']' +
        ' TO ' + '[' + dpr.name + ']'
      ) AS GRANT_STMT
    FROM sys.database_permissions AS dp
      INNER JOIN sys.objects AS o ON dp.major_id=o.object_id
      INNER JOIN sys.schemas AS s ON o.schema_id = s.schema_id
      INNER JOIN sys.database_principals AS dpr ON dp.grantee_principal_id=dpr.principal_id
    WHERE dpr.name NOT IN ('public','guest')
    --  AND o.name IN ('My_Procedure')      -- Uncomment to filter to specific object(s)
    --  AND dp.permission_name='EXECUTE'    -- Uncomment to filter to just the EXECUTEs
    

    This will spit out a bunch of commands (GRANT/DENY) for each of the permissions in the database. From this, you can copy-and-paste them into another query window and execute, to generate the same permissions that were in place on the original. For example:

    GRANT EXECUTE ON [Exposed].[EmployeePunchoutReservationRetrieve] TO [CustomerAgentRole]
    GRANT EXECUTE ON [Exposed].[EmployeePunchoutReservationStore] TO [CustomerAgentRole]
    GRANT EXECUTE ON [Exposed].[EmployeePunchoutSendOrderLogStore] TO [CustomerAgentRole]
    GRANT EXECUTE ON [Exposed].[EmployeeReportSubscriptions] TO [CustomerAgentRole]
    

    Note the bottom line, commented out, that's filtering on permission_name. Un-commenting that line will cause the query to only spit out the EXECUTE permissions (i.e., those for stored procedures).

提交回复
热议问题