Wednesday, October 28, 2009

Grant EXECUTE Permissions on all Stored Procedures to a Single User

I needed a quick way to grant EXEC rights to a read only reporting user I have in a SQL database. With this I was able to do it for all the SP’s that met my wildcard.

-- Originally written by Jeremiah Peschka on SQLServerPedia.com
DECLARE @sql AS NVARCHAR(MAX);
DECLARE @newline AS NVARCHAR(2);
DECLARE @user_name AS NVARCHAR(100);
DECLARE @sproc_name_pattern AS NVARCHAR(10);

SET @sql = N''
SET @newline = NCHAR(13) + NCHAR(10);
SET @user_name = N'jeremiah';
-- escaping _ prevents it from matching any single character
-- including the wildcard makes this much more portable between DBs
SET @sproc_name_pattern = N'sproc[_]%';

-- using QUOTENAME will properly escape any object names with spaces
-- or other funky characters
SELECT @sql = @sql
+ N'GRANT EXECUTE ON '
+ QUOTENAME(OBJECT_SCHEMA_NAME([object_id])) + '.'
+ QUOTENAME([name])
+ N' TO '
+ QUOTENAME(@user_name)
+ N';'
+ @newline + @newline
FROM sys.procedures
WHERE [name] LIKE @sproc_name_pattern;

-- this is my version of debug code, I usually run it once with the PRINT intact
-- before I actually use sp_executesql
--PRINT @sql;

EXEC sp_executesql @sql;

No comments:

Post a Comment