实现SQL脚本的最佳方法是什么,该脚本将对数据库中所有用户表的数据库角色授予选择,引用,插入,更新和删除权限?
理想情况下,此脚本可以多次运行,因为新表已添加到数据库中。 SQL Server Management Studio为单个数据库对象生成脚本,但我正在寻找更多“即发即弃”的脚本。
答案 0 :(得分:2)
我确信有一种更简单的方法,但您可以遍历数据库中的sysobjects表,并为存在的任何用户表对象授予权限。然后,无论何时添加新表,您都可以多次运行。
答案 1 :(得分:1)
Zimmerman博士在这里走在正确的轨道上。我期待编写一个存储过程,其中有一个游标循环遍历用户对象,使用execute immediate来影响授权。像这样:
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
答案 2 :(得分: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;'
通过一些游戏,也可以将角色名称转换为参数。
答案 3 :(得分: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
答案 4 :(得分: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