【问题标题】:Recreating security on a restored database?在恢复的数据库上重新创建安全性?
【发布时间】:2013-09-27 13:11:49
【问题描述】:
我们经常负责在生产环境和开发环境之间备份和恢复数据库。此任务中最繁琐的部分是当服务器位于不同区域时,在 SQL 中“一个一个”地重新创建数据库用户。
我正在寻找一种方法来检索特定数据库上的所有用户(Windows 用户和组、SQL 用户和角色)以及他们当前的权限级别,然后在数据库恢复后以某种方式使用这些结果重新创建权限。
谁能帮助我朝着正确的方向开始?
问候,
马修
【问题讨论】:
标签:
sql
sql-server
scripting
permissions
【解决方案2】:
以下查询应该:
创建一个临时表来保存要执行的查询
使用查询加载该临时表以添加所有登录名
使用查询加载该临时表以添加所有用户(用于登录)
使用查询加载该临时表以添加所有权限(对于表)
然后它会打印出所有这些语句,您应该能够将它们复制到新环境中的查询窗口并执行。
希望这对您来说是一个很好的起点。
if object_id('dbo.tempUsers') is not null
Drop table dbo.tempUsers
Create table tempUsers(ID int identity , Queries Varchar(255))
Insert into tempUsers(Queries)
select 'Create login [' + su.name + '] with password ' + su.password
FROM sys.sysusers su
Insert into tempUsers(Queries)
select 'Create user [' + su.name + '] for login [' + su.password + ']'
FROM sys.sysusers su
Insert into tempUsers(Queries)
select 'GRANT ' + dp.permission_name collate latin1_general_cs_as
+ ' ON ' + s.name + '.' + o.name + ' TO ' + '[' + dpr.name + ']'
FROM sys.database_permissions AS dp
INNER JOIN sys.objects AS o ON dp.major_id=o.object_id
INNER JOIN sys.schemas AS s ON o.schema_id = s.schema_id
INNER JOIN sys.database_principals AS dpr ON dp.grantee_principal_id=dpr.principal_id
where o.type = 'U'
declare @count int, @max int, @query Varchar(255)
set @count =1
set @max = (Select max(ID) from tempUsers)
set @query = (Select Queries from tempUsers where ID = @count)
while(@count < @max)
begin
print(@query)
set @count += 1
set @query = (Select Queries from tempUsers where ID = @count)
end