How to script SQL server database role?

前端 未结 8 1120
遇见更好的自我
遇见更好的自我 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条回答
  • You can get what you need with a script like this:

    declare @RoleName varchar(50) = 'RoleName'
    
    declare @Script varchar(max) = 'CREATE ROLE ' + @RoleName + char(13)
    select @script = @script + 'GRANT ' + prm.permission_name + ' ON ' + OBJECT_NAME(major_id) + ' TO ' + rol.name + char(13) COLLATE Latin1_General_CI_AS 
    from sys.database_permissions prm
        join sys.database_principals rol on
            prm.grantee_principal_id = rol.principal_id
    where rol.name = @RoleName
    
    print @script
    
    0 讨论(0)
  • 2021-02-01 18:40
    -- Use this if you have a lot of permissions assigned to a Database Role
    -- Before running, set results to Text
    
    SET NOCOUNT ON
    
    Use MyDB;  -- CHANGE DATABASE NAME
    
    DECLARE @RoleName varchar(50) = 'sp_exec' --- change role name here
    
    SELECT 'CREATE ROLE [' + @RoleName + '];'+ char(13)
    
    SELECT  'GRANT ' + prm.permission_name + ' ON [' + 
    OBJECT_NAME(major_id) + '] TO [' + rol.name + '] ;' + char(13) COLLATE Latin1_General_CI_AS
    
    from sys.database_permissions prm
    
        join sys.database_principals rol on
    
            prm.grantee_principal_id = rol.principal_id
    
    where rol.name = @RoleName
    
    0 讨论(0)
提交回复
热议问题