2

实现一个 SQL 脚本的最佳方法是向数据库中所有用户表的数据库角色授予选择、引用、插入、更新和删除权限?

理想情况下,该脚本可以运行多次,因为新表已添加到数据库中。SQL Server Management Studio 为单个数据库对象生成脚本,但我正在寻找更多的“即发即弃”脚本。

4

5 回答 5

2

我确信有一种更简单的方法,但是您可以循环访问数据库中的 sysobjects 表并授予对任何存在的用户表对象的权限。然后,您可以在添加新表时多次运行。

于 2008-09-04T21:30:34.920 回答
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 '+@role)

    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
于 2008-09-05T14:20:54.880 回答
1

有一个名为 sp_MSforeachtable 的未记录 MS 过程,您可以使用它肯定是在 2000 年和 2005 年。

要授予选择权限,用法将是:

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

要授予其他权限,要么为每个权限添加一个新语句,要么将它们添加到命令中,如下所示:

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

稍微玩一下,也可以将角色名称转换为参数。

于 2008-09-09T21:02:06.457 回答
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
于 2008-09-05T14:28:16.767 回答
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
于 2009-11-02T19:09:49.050 回答