How to script SQL server database role?

前端 未结 8 1118
遇见更好的自我
遇见更好的自我 2021-02-01 17:49

I need to make a script to copy one particular database role from one SQL server to another.

Is there an easy way to generate a script that creates the role and all the

8条回答
  •  一整个雨季
    2021-02-01 18:25

    This script generates GRANT statements for your roles. I like, that it supports column leven permissions. It has to be adapted to your need (ie. improve for more complex databases, concatenate statements and execute, include create statement for your role). But just to give you an idea:

    SELECT 'GRANT ' + database_permissions.permission_name + ' ON ' +
        CASE database_permissions.class_desc
            WHEN 'SCHEMA' THEN schema_name(major_id)
            WHEN 'OBJECT_OR_COLUMN' THEN
                CASE WHEN minor_id = 0 THEN object_name(major_id) COLLATE Latin1_General_CI_AS_KS_WS
                ELSE (SELECT object_name(object_id) + ' ('+ name + ')'
                      FROM sys.columns 
                      WHERE object_id = database_permissions.major_id 
                      AND column_id = database_permissions.minor_id) end
            ELSE 'other' 
        END + 
        ' TO ' + database_principals.name COLLATE Latin1_General_CI_AS_KS_WS
    FROM sys.database_permissions
    JOIN sys.database_principals
    ON database_permissions.grantee_principal_id = database_principals.principal_id
    LEFT JOIN sys.objects --left because it is possible that it is a schema
    ON objects.object_id = database_permissions.major_id
    WHERE database_permissions.major_id > 0
    AND permission_name in ('SELECT','INSERT','UPDATE','DELETE')
    

提交回复
热议问题