Search code examples
sqlsql-server-2008permissionssql-grant

SQL Server how do I run a dynamic statement


I have a stored procedure that generates grant scripts for each permission in our database. After the grant scripts are generated I was wondering how do I run the scripts automatically? (My goal is to create the scripts and then run the scripts automatically)

Here is my procedure:

 PROCEDURE [dbo].[IPAM_GRANT_DB_PERMS_SCRIPT]
    @GRANTACTION NVARCHAR(20),
    @TYPE NVARCHAR(20),
    @ACTION INT
AS
    DECLARE @SQL NVARCHAR(2000)
BEGIN
    SET @SQL = ''

    SELECT @SQL = (SELECT 'GRANT ' + @GRANTACTION + ' ON ' + 'a.name TO ' + user_name(b.uid) FROM SYSOBJECTS a ,SYSPROTECTS b WHERE a.TYPE IN (@TYPE) AND USER_NAME(b.UID) <> 'public' AND a.NAME NOT LIKE 'dt_%' AND a.ID=b.ID AND ACTION=@ACTION

    EXEC @SQL
    PRINT @SQL
END

And here is what I had in mind (will this work?)

PROCEDURE IPAM_EX_PERMS
AS
BEGIN
    PRINT '--Initiating DELETE permissions--'
    EXEC IPAM_GRANT_DB_PERMS_SCRIPT 'DELETE', 'U', 196
    PRINT '--Completed DELETE permissions--'
    PRINT ''
    PRINT ''
    PRINT '--Initiating INSERT permissions--'
    EXEC IPAM_GRANT_DB_PERMS_SCRIPT 'INSERT', 'U', 195
    PRINT '--Completed INSERT permissions--'
    PRINT ''
    PRINT ''
    PRINT '--Initiating SELECT permissions--'
    EXEC IPAM_GRANT_DB_PERMS_SCRIPT 'SELECT', 'U', 193
    PRINT '--Completed SELECT permissions--'
    PRINT ''
    PRINT ''
    PRINT '--Initiating UPDATE permissions--'
    EXEC IPAM_GRANT_DB_PERMS_SCRIPT 'UPDATE', 'U', 197
    PRINT '--Completed UPDATE permissions--'
    PRINT ''
    PRINT ''
    PRINT '--Initiating EXECUTE permissions on Procedures--'
    EXEC IPAM_GRANT_DB_PERMS_SCRIPT 'EXECUTE', 'P', 224
    PRINT '--Completed EXECUTE permissions on Procedures--'
    PRINT ''
    PRINT ''
    PRINT '--Initiating EXECUTE permissions on Functions--'
    EXEC IPAM_GRANT_DB_PERMS_SCRIPT 'EXECUTE', 'Fn', 224
    PRINT '--Completed EXECUTE permissions on Functions--'
    PRINT ''
    PRINT ''
    PRINT ''
    PRINT 'Finished processing grant permissions on the IPAM DB' 
END
GO

Solution

  • I am closing this question, due to the fact that it would be redundant to run this script on a new database if there is no permission currently set.