I have many security accounts on the sql database and i want to remove/add roles to them based on a simple string comparison.
- Basically i want to list all
accounts - Filter out accounts that DON’T start
with “MyDomain\” - Remove role A.
- Add role B.
What i found out by now is that i use sp_helprolemember to list all the accounts and sp_addrolemember and sp_droprolemember. My problem is that i dont know how to “get” the output from sp_helprolemember and work with it.
My first attemt at a soltuion based of feedback.
DROP TABLE [dbo].[XTemp] create table XTemp(DbRole sysname,MemberName sysname,MemberSID varbinary(85) ) insert XTemp exec sp_helprolemember select * from XTemp
I made a permanent table to make it simpler to test and debug.
SELECT [DbRole]
,[MemberName]
,[MemberSID]
FROM [ARTICLE].[dbo].[XTemp]
WHERE MemberName like Domain\%'
exec sp_addrolemember 'OldRole MemberName
Assuming that you’re using SQL 2005 or later, and executing
sp_helprolememberwithout parameters, this is the query thatsp_helprolememberruns (extracted usingsp_helptext):This should enable you to collect the information you need into a temp table.
If you’d rather stick to documented behaviour, you can store the output of the SP into a temp table:
EDIT
There are two ways to use this data to amend your system. One is using a cursor:
The other is using dynamic SQL:
As you can see the dynamic SQL version is more compact but requires more effort to maintain.
Remember that after you execute either statement, the data you extracted from
sp_helprolememberinto a table is no longer up to date, and should probably be refreshed.