SQL Server – Apply Custom Server Role to Existing Databases

rolesql-server-2012

I needed a custom SQL Server role which has readonly access to all databases, regardless of whether a database is existing or is newly created.

The role is not a problem. The problem is that the role will not be applied to existing databases.
If I create a new database, the role is applied and does working as I expected.

I assume there will be some system stored procedure that will be run at the moment, a new database is created.

Is there any possibility to apply the custom server role afterwards to databases which are existed before i created the custom server role?

I am using SQL Server 2012.

Thanks in advance

Best Answer

I suspect that you are not actually creating a SERVER ROLE but in fact are creating a DATABASE ROLE in the model database. I looked under server roles for a bit and could find nothing that would grant read access to a database (old or new). I can see ALTER ANY DATABASE, CREATE ANY DATABASE and VIEW ANY DATABASE but nothing about read/write of the tables.

If what I suspect is correct and you are creating a role in the model database then it would have exactly the effect you are discussing. You would see the role show up in all new databases but not the old ones. Unfortunately the only way around this is to create the role in each of the existing databases. Fortunately this is fairly easy.

First thing would be to generate a script that creates the role either by using a scripting tool, creating it in the GUI and hitting the script button, or using the generate scripts option (right click on the database).

Once you have the script for the role you can either manually run it on each of your existing databases (probably ok if you only have <50 or so) or you can generate some dynamic SQL to run the script for you.