The other day I came across something where I needed to grant view definition rights to a specific user for one single DB. Now, there are several different ways to achieve this but I decided to dabble in just writing some code to take care of it for me. Others might have something very similar or different mechanisms to do such but for me I used the following code:
The basic gist is as follows:
- Create Temp Table – you can use a # table just drop it when done with it
- Declaration of Variables
- Insert data into temp table – only want to grab the procedures and nothing with a _dt
- Grab all of the procedures found in the DB and dynamically set the grant permissions to a SQL string
- Execute the SQL string
- Restart the counter and reset the name variable just for good measure
- Select the temp table to view what was just granted view definition to
Code in doing this:
DECLARE @PermTable TABLE
(
PK_ID INT IDENTITY(1, 1)
NOT NULL
PRIMARY KEY CLUSTERED ,
[name] SYSNAME
)
–declare variables
DECLARE @name SYSNAME ,
@RowCount INT ,
@RecordCount INT ,
@strSQL VARCHAR(2000)
INSERT INTO @PermTable
(
[name]
)
SELECT ROUTINE_SCHEMA + ‘.’ + ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = ‘Procedure’
AND ROUTINE_NAME NOT LIKE ‘dt_%’
— counters for while
SET @RecordCount = ( SELECT COUNT(*)
FROM @PermTable
)
SET @RowCount = 1
WHILE ( @RowCount < @RecordCount + 1 )
BEGIN
SELECT @name = [name]
FROM @PermTable
WHERE PK_ID = @RowCount
SET @strSQL = N’Grant VIEW Definition on ‘
+ RTRIM(CAST(@name AS VARCHAR(128))) + ‘ to [User]’
–Execute the Sql
EXEC(@strSQL)
–Restart the Counter
SET @RowCount = @RowCount + 1
–Never know so why not reset
SET @name = NULL
END
SELECT *
FROM @PermTable
Hope this helps; cheers.