We help IT Professionals succeed at work.
Get Started

SQL - Add mappings for existing login to multiple DBs

159 Views
Last Modified: 2015-02-26
I have a MS SQL Server 2005 server. I have a login that has db_datareader and db_datadenywriter to one of the DBs on that server. I need to add these same mappings to about 40 more DBs, and I don't want to do it manually... especially since this is for our lab and I'll have to do the same in our production environment later.

All of the DBs are named following a pattern, and they all end with the same last three letters.

I'm trying the following:
EXEC sp_MSforeachdb N'IF ''?'' LIKE ''%XYZ''
BEGIN
EXEC sp_addrolemember ''db_datareader'', ''MYDOMAIN\MyServiceAccount''
EXEC sp_addrolemember ''db_denydatawriter'', ''MYDOMAIN\MyServiceAccount''
END';

Open in new window


This runs successfully, but when I check the mappings for that account, no changes appear to have been made. What am I doing wrong? Or is there a better way to accomplish this?

Thanks in advance.
Comment
Watch Question
Senior Database Administrator
CERTIFIED EXPERT
Commented:
This problem has been solved!
Unlock 3 Answers and 7 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE