“重命名”数据库角色

时间:2015-10-02 08:02:48

标签: sql-server tsql

由于我不想详细说明的原因,已经决定重命名我们的数据库角色。 我知道没有简单的方法可以重命名角色(不知道为什么), 但我想出了这个解决方案:

create table #RoleAssignment (id int identity, RoleName varchar(256), UserName varchar(256))
insert into #RoleAssignment
select roles.name as RoleName, users.name as UserName 
  from sys.sysusers as roles
  join sys.database_role_members as members
    on members.role_principal_id = roles.uid
  join sys.sysusers as users
    on users.uid = members.member_principal_id
 where roles.issqlrole = 1
   and roles.name like 'OldRolePrefix_%'

declare @id int = null
declare @RoleName varchar(256)
declare @NewRoleName varchar(256)
declare @UserName varchar(256)

select top 1 @id = id, @RoleName = RoleName, @UserName = UserName,@NewRoleName = replace(RoleName,'OldRolePrefix_','NewRolePrefix_') from #RoleAssignment

while (@id is not null)
begin
    execute sp_executesql N'sp_droprolemember @InSPRoleName, @InSPUserName',N'@InSPRoleName varchar(256), @InSPUserName varchar(256)', @InSPRoleName = @RoleName, @InSPUserName = @UserName 
    execute sp_executesql N'sp_addrolemember @InSPRoleName, @InSPUserName',N'@InSPRoleName varchar(256), @InSPUserName varchar(256)', @InSPRoleName = @NewRoleName, @InSPUserName = @UserName 
    delete from #RoleAssignment where id = @id
    set @id = null
    select top 1 @id = id, @RoleName = RoleName, @UserName = UserName from     #RoleAssignment
end

在此之后,运行设置角色权限的脚本。

我对此进行了测试,总体而言是有效的。 但即使在读取和测试后我也不确定: 我忘记了什么吗?

非常感谢您的任何想法/见解

1 个答案:

答案 0 :(得分:8)

您没有指定正在使用的SQL Server版本,但在SQL Server 2008及更高版本中,您可以使用ALTER ROLE重命名角色:

ALTER ROLE OldRoleName WITH NAME = NewRoleName;