If you've worked with SQL server for any amount of time, you've probably encountered the need to grant permissions to objects in your database. Often, you create database roles and assign permissions to those roles. You can easily add users to those roles to inherit those permissions. If you've tried to use the GUI to grant permissions, you've also likely been frustrated by the amount of clicks required to grant permissions.
Here are a couple ways to easily grant permissions to a database role in SQL 2005 or higher.
First, create your database role. You can use the code below:
CREATE ROLE Test_Role;
Next, grant "Execute" permissions on all objects in the database to that role.
GRANT EXEC TO Test_Role;
That's pretty straightforward, but if you need to grant permissions on a particular schema and not others, you will want to refine this a little bit, for example to grant execute permissions on a specific schema:
GRANT EXEC ON Schema::dbo TO Test_Role;
If you need to be even more granular in permissions, you can also use a cursor such as the following to grant permissions on each object. (This also has the advantage of working against versions lower than SQL 2005 with some minor changes to the SELECT statement in the cursor.) The following example will grant execute permissions on all stored procedures with a name not beginning with "dt_" to the "Test_Role" role.
DECLARE @SQL NVARCHAR(3000) DECLARE @RoleName NVARCHAR(100) SELECT @RoleName = 'Test_Role' DECLARE GrantExec_Cursor CURSOR FAST_FORWARD READ_ONLY FOR SELECT 'GRANT EXEC ON [' + ROUTINE_SCHEMA + '].[' + ROUTINE_NAME + '] TO [' + @RoleName + '];' FROM INFORMATION_SCHEMA.Routines WHERE ROUTINE_TYPE = 'Procedure' AND ROUTINE_NAME NOT LIKE 'dt[_]%' OPEN GrantExec_Cursor FETCH NEXT FROM GrantExec_Cursor INTO @SQL WHILE @@FETCH_STATUS = 0 BEGIN --Grant Permissions EXEC(@SQL) FETCH NEXT FROM GrantExec_Cursor INTO @SQL END --Grant Permissions CLOSE GrantExec_Cursor DEALLOCATE GrantExec_Cursor GO
The main advantage of the cursor method is that you can tailor your set of stored procedures easily to exclude or include them based on your criteria. If there are certain stored procedures this role should never call, you can easily filter them out in your WHERE clause.
Of course, this is by no means an exhaustive set of ways to grant permissions, but if you just need to quickly grant execute permissions to a database role, the methods above will help in most cases. If you have any methods that work well for you, feel free to post them in the comments.