SQL Server如何运行动态语句

时间:2011-01-13 16:28:38

标签: sql sql-server-2008 permissions grant

我有一个存储过程,为我们数据库中的每个权限生成授权脚本。生成授权脚本后,我想知道如何自动运行脚本? (我的目标是创建脚本,然后自动运行脚本)

这是我的程序:

 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

这就是我的想法(这会起作用吗?)

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

2 个答案:

答案 0 :(得分:0)

我认为只要你改变

就行了
exec @SQL

exec (@SQL)

如果说明不够,请尝试以下示例:

declare @foo varchar(30)
set @foo = (select 'select 42')
exec (@foo)

答案 1 :(得分:0)

我正在结束这个问题,因为如果当前没有设置权限,在新数据库上运行此脚本将是多余的。