Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ALTER ROLE to drop all members

I am using SQL Server 2012, and my main goal is to programmatically DROP ROLE, but that cannot be done unless the role is empty, so how can I use T-SQL to first drop all members of a role?

  • I can find all members of a role:

    SELECT members.[name] 
    FROM sys.database_role_members AS rolemembers
        JOIN sys.database_principals AS roles 
            ON roles.[principal_id] = rolemembers.[role_principal_id]
        JOIN sys.database_principals AS members 
            ON members.[principal_id] = rolemembers.[member_principal_id]
    WHERE roles.[name]=@rolename
    
  • Members can be dropped using:

    ALTER ROLE role_name DROP MEMBER user_name
    

How can I combine these two? Or is there another way to do what I'm trying to do?

(Also, I'm not sure if this is important, but I will be using this in an Entity Framework 6 migration)

like image 739
jjj Avatar asked Apr 30 '15 19:04

jjj


2 Answers

Here's how I would combine the two:

DECLARE @rolename sysname = 'role_name';
DECLARE @cmd AS NVARCHAR(MAX) = N'';

SELECT @cmd = @cmd + '
    ALTER ROLE ' + QUOTENAME(@rolename) + ' DROP MEMBER ' + QUOTENAME(members.[name]) + ';'
FROM sys.database_role_members AS rolemembers
    JOIN sys.database_principals AS roles 
        ON roles.[principal_id] = rolemembers.[role_principal_id]
    JOIN sys.database_principals AS members 
        ON members.[principal_id] = rolemembers.[member_principal_id]
WHERE roles.[name]=@rolename

EXEC(@cmd);

This creates a string with your ALTER ROLE command for every row (user) in your query, concatenates them all together into one big string with all of those commands and then dynamically executes them.

like image 58
RBarryYoung Avatar answered Oct 02 '22 08:10

RBarryYoung


There is special sp (sp_droprolemember) in sql server. I hope, it solves you problem.

like image 39
Vladimir Semashkin Avatar answered Oct 02 '22 08:10

Vladimir Semashkin