2008-09-04 47 views
2

實現SQL腳本的最佳方式是什麼?它將授予數據庫中所有用戶表上的數據庫角色的選擇,引用,插入,更新和刪除權限?實現SQL腳本的最佳方式是什麼?它將授予數據庫中所有用戶表上數據庫角色的權限?

理想情況下,此腳本可以多次運行,因爲新表已添加到數據庫中。 SQL Server Management Studio爲單個數據庫對象生成腳本,但我正在尋找更多的「即忘即忘」腳本。

+1

這不就是db_datareader和db_datawriter角色的用途嗎?或者當這個問題被問到時它們不存在? – 2015-09-17 13:36:59

回答

1

Zimmerman博士在這裏的正確軌道上。我希望編寫一個存儲過程,該存儲過程使用立即執行來影響授予的遊標循環訪問用戶對象。事情是這樣的:

IF EXISTS (
    SELECT 1 FROM sysobjects 
    WHERE name = 'sp_grantastic' 
    AND type = 'P' 
) 
DROP PROCEDURE sp_grantastic 
GO 
CREATE PROCEDURE sp_grantastic 
AS 
DECLARE 
@object_name VARCHAR(30) 
,@time  VARCHAR(8) 
,@rights  VARCHAR(20) 
,@role  VARCHAR(20) 

DECLARE c_objects CURSOR FOR 
    SELECT name 
    FROM sysobjects 
    WHERE type IN ('P', 'U', 'V') 
    FOR READ ONLY 

BEGIN 

    SELECT @rights = 'ALL' 
      ,@role = 'PUBLIC' 

    OPEN c_objects 
    WHILE (1=1) 
    BEGIN 
     FETCH c_objects INTO @object_name 
     IF @@SQLSTATUS <> 0 BREAK 

     SELECT @time = CONVERT(VARCHAR, GetDate(), 108) 
     PRINT '[%1!] hitting up object %2!', @time, @object_name 
     EXECUTE('GRANT '+ @rights +' ON '+ @object_name+' TO '[email protected]) 

    END 

    PRINT '[%1!] fin!', @time 

    CLOSE c_objects 
    DEALLOCATE CURSOR c_objects 
END 
GO 
GRANT ALL ON sp_grantastic TO PUBLIC 
GO 

然後你可以射後不理:

EXEC sp_grantastic 
2

我確定有一種更簡單的方法,但是可以循環訪問數據庫中的sysobjects表,並將權限授予存在的任何用戶表對象。然後,每當添加新表時,您都可以多次運行該程序。

0

我們使用類似的事情,我的工作。遍歷系統的每個表,視圖,存儲過程。

CREATE PROCEDURE dbo.SP_GrantFullAccess 
    @username varchar(300) 
AS 

DECLARE @on varchar(300) 
DECLARE @count int 
SET @count = 0 

PRINT 'Granting access to user ' + @username + ' on the following objects:' 

DECLARE c CURSOR FOR 
SELECT name FROM sysobjects WHERE type IN('U', 'V', 'SP', 'P') ORDER BY name 
OPEN c 
FETCH NEXT FROM c INTO @on 
WHILE @@FETCH_STATUS = 0 
BEGIN 
SET @count = @count + 1 
EXEC('GRANT ALL ON [' + @on + '] TO [' + @username + ']') 
--PRINT 'GRANT ALL ON [' + @on + '] TO ' + @username 
PRINT @on 
FETCH NEXT FROM c INTO @on 
END 
CLOSE c 
DEALLOCATE c 

PRINT 'Granted access to ' + cast(@count as varchar(4)) + ' object(s).' 
GO 
2

有一個稱爲sp_MSforeachtable,你可以用這絕對是在2000年和2005年

授予SELECT權限無證MS程序的用法是:

EXECUTE sp_MSforeachtable @command1=' Grant Select on ? to RoleName' 

授予其他權限要麼有每個新的聲明或只是將它們添加到像這樣的命令:

EXECUTE sp_MSforeachtable @command1=' Grant Select on ? to RoleName; Grant Delete on ? to RoleName;' 

隨着一段時間的玩耍,可能會將角色名稱變成參數。

0
use [YourDb] 
GO 
exec sp_MSforeachtable @command1= 
    "GRANT DELETE, INSERT, REFERENCES, SELECT, UPDATE ON ? TO Admins, Mgmt", 
    @whereand = " and o.name like 'tbl_%'" 
GO 

use [YourDb] 
GO 
exec sp_MSforeachtable @command1= 
    "GRANT REFERENCES, SELECT ON ? TO Employee, public", 
    @whereand = " and o.name like 'tbl_%'" 
GO 
相關問題