Friday, March 1, 2013

Generate scripts to create DB role and its securables from existing DB

declare @RoleName varchar(50) = 'RoleName'

-- Create script to create DB Role
select 'CREATE ROLE [' + @RoleName + ']' + char(13) + 'GO'

-- Create script to grant pemission of securable of the DB Role
select 'GRANT ' + prm.permission_name + ' ON [' + OBJECT_NAME(major_id) + '] TO [' + rol.name + ']' + char(13) COLLATE Latin1_General_CI_AS + 'GO'
from sys.database_permissions prm
    join sys.database_principals rol on
        prm.grantee_principal_id = rol.principal_id
where rol.name = @RoleName

No comments:

Post a Comment