Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - Give a Login Permission for Read Access to All Existing and Future Databases

I have a stored procedure that finds all the existing databases and reads from a table in each one.

Is there a way I can give a login read access to all databases, and to all future databases i.e., I won't have to do anything when a new database is added?

Is there a server role that would work? Is there a way to make a SQL agent job add the permissions on any new databases? Or is there some other method?

like image 513
Greg Avatar asked Aug 23 '10 18:08

Greg


People also ask

How do you provide read access to all databases in SQL Server?

Expand Security - Logins, then Right Click on login and then click Properties. Go to User Mapping tab and select the database on which you want to give permission and at bottom select db_datareader as shown below. Click Ok and you're done.


1 Answers

For new databases, add the user in the model database. This is used as the template for all new databases.

USE model
CREATE USER ... FROM LOGIN...
EXEC sp_addrolemember 'db_datareader', '...'

For existing databases, use sp_MSForEachDb

EXEC sp_MSForEachDb '
 USE ?
 CREATE USER ... FROM LOGIN...  
 EXEC sp_addrolemember ''db_datareader'', ''...''
'
like image 134
gbn Avatar answered Nov 15 '22 17:11

gbn