在SQL Server 2005中,如何将用户名的变量用于GRANT或DENY对具有数据库的对象的权限?我试过了:
DECLARE @username varchar(30)
SET @username = 'DOMAIN\UserName'
GRANT SELECT ON [mytable] TO @username
GRANT UPDATE([field one], [field two], [field three]) ON [mytable] TO @username
我得到Incorrect syntax near '@username'
,然后我把它包裹在[和]
GRANT SELECT ON [mytable] TO [@username]
然而,这会产生Cannot find the user '@username', because it does not exist or you do not have permission
。如何在不输入每个语句的用户名的情况下执行此操作?我想这样做是为了减少任何拼写错误的机会(这可能导致错误的用户获得权限设置)
答案 0 :(得分:7)
如果要查看将要执行的内容,则需要动态sql,将EXEC更改为PRINT 添加了引号功能,因为您需要围绕域用户使用括号
DECLARE @username varchar(30)
SET @username = 'DOMAIN\UserName'
SET @username = quotename(@username)
exec ('GRANT SELECT ON [mytable] TO ' + @username )
exec ('GRANT UPDATE([field one], [field two], [field three]) ON [mytable] TO ' + @username )
答案 1 :(得分:1)
在这种情况下是否会使用动态SQL工作?
DECLARE @sql VARCHAR(2000)
SET @sql = 'GRANT SELECT ON [mytable] TO ' + @username
EXEC @sql
答案 2 :(得分:1)
从Yoopergeek更新答案,您可以
DECLARE @sql VARCHAR(2000)
SET @sql = 'GRANT SELECT ON [mytable] TO [' + Replace(@username, '[', '\[') + ']' + Char(13) + Char(10)
SET @sql = 'GRANT UPDATE([field one], [field two], [field three]) ON [mytable] TO [' + Replace(@username, '[', '\[') + ']'
PRINT @sql
EXEC @sql