在SQL Server 2005中使用GRANT和DENY的变量(Using variables with GRANT and DENY in SQL Server 2005)

编程入门 行业动态 更新时间:2024-10-27 00:24:36
在SQL Server 2005中使用GRANT和DENY的变量(Using variables with GRANT and DENY in SQL Server 2005)

在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'得到了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 。 我怎样才能做到这一点,而不必输入每个语句的用户名? 我想这样做是为了减少任何错字的机会(这可能会导致错误的用户获得权限设置)

In SQL Server 2005 how can you use a variable for the username to GRANT or DENY permissions to objects withing the database? I have tried:

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

I get Incorrect syntax near '@username', so then I wrapped it in [ and ]

GRANT SELECT ON [mytable] TO [@username]

However this then results in Cannot find the user '@username', because it does not exist or you do not have permission. How can I do this without having to type out the username for each statement? I want to do this to reduce chances of any typo's (which could result in the wrong user getting permissions set)

最满意答案

你需要动态sql,如果你想查看执行什么内容,将EXEC更改为PRINT添加quotename函数,因为你需要围绕域用户使用括号

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 )

you need dynamic sql, change EXEC to PRINT if you want to see what will get executed added the quotename function because you need brackets around domain users

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 )

更多推荐

本文发布于:2023-07-25 10:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1259984.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   Server   SQL   variables   DENY

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!