2009-06-18 51 views
3

在SQL Server 2005中,如何使用變量作爲用戶名來使用GRANT或DENY權限訪問數據庫對象?我曾嘗試:在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。我怎樣才能做到這一點,而不必輸入每個語句的用戶名?我想要這樣做,以減少任何錯字的機會(這可能會導致錯誤的用戶獲得權限設置)

回答

7

你需要動態SQL,改變EXEC到打印如果你想看到什麼都會得到執行 加入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) 
1

在這種情況下將使用動態SQL工作?

DECLARE @sql VARCHAR(2000) 
SET @sql = 'GRANT SELECT ON [mytable] TO ' + @username 
EXEC @sql 
+0

只要記住保護代碼免受SQL注入。 – 2009-06-18 12:51:02

+0

這將導致一個錯誤: 未能找到存儲過程 'GRANT SELECT ON [MYTABLE] TO域\用戶名' – SamWM 2009-06-18 12:52:58

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