Follow sqlserver-dba.com

Subscribe to RSS feed  Follow @jackvamvas - Twitter

*Use the Comments section for questions

SQLServer-DBA.com Links

Dba_db2_button

dba-ninja.com

SQL Server DBA Jobs

How to Script SQL database role permissions and securables

15 October,2014 by Tom Collins

Question : How can I script database role permissions?  I’ve created the database role but need to migrate the database role  permissions.

Answer: Use this DBA script on the source database . Add the database role name as a value to the @DBRoleName  variable.Copy and paste the GRANT EXECUTE statements and execute them on the target database

 Script database role permissions

The script will output the CREATE ROLE statement and then the GRANT statement. You'll need to execute these statements to apply the commands 

SET NOCOUNT ON

Use myDB;  -- ADJUST DB NAME

DECLARE @RoleName varchar(50) = 'myRole' --- PLACE ROLE NAME

SELECT 'CREATE ROLE ' + @RoleName + ';'+ char(13)

SELECT  'GRANT ' + prm.permission_name + ' ON [' + s.name + + '].[' + 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
JOIN sys.objects AS o  ON prm.major_id = o.object_id  
JOIN sys.schemas AS s  ON o.schema_id = s.schema_id
where rol.name = @RoleName





Output will be similar to:

CREATE ROLE myRole;

GRANT SELECT ON [dbo].[Contact] TO [myRole] ;
GRANT SELECT ON [dbo].[myTable2] TO [myRole] ;

Read More on database roles

SQL Server database roles and GDPR

SQL Database roles and members

Powershell sql server security audit - SQL Server DBA

How to create a SQL Server Security Audit - SQL Server DBA


Author: Tom Collins (http://www.sqlserver-dba.com)


Share:

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment on How to Script SQL database role permissions and securables


sqlserver-dba.com | SQL Server Performance Tuning | SQL Server DBA:Everything | FAQ | Contact|Copyright & Disclaimer