views:

24

answers:

3

How do I set a Windows login on SQL Server so that it has read-only access to any database on the server, and will default to having read-only access to any subsequently added database.

I would prefer T-SQL code.

I am using SQL 2000

+1  A: 

I would suggest you create a new group and make all user accounts belong to it. Then grant that role the db_datareader permission in all your databases.

To create a new server role called 'EVERYONE': EXEC sp_addrole 'EVERYONE'

...then put all user accounts into it (you can find the T-SQL to do this from this article, but you'll have to dig it out--my firewall won't let me post that fragment here!).

...then make the role a member of each database's db_datareader role:

EXEC sp_msforeachdb 'USE [?] EXEC sp_addrolemember [db_datareader], [EVERYONE]';

(*Note that for security reasons you probably do not want the full db_datareader permissions on the system databases like 'master', so you could might remove the EVERYONE group from those.*)

Now you just need to remember:

  1. When you create a new user login, add it to the 'EVERYONE' role: EXEC sp_addrolemember [EVERYONE], [new_user_name]
  2. When you create a new database, add 'EVERYONE' to the 'db_datareader' role: USE [new_db_name]; EXEC sp_addrolemember [db_datareader], [EVERYONE]
ewall
sp_addrole creates a database role, not a server role. It's not currently possible to create server roles in any version of MSSQL.
Pondlife
Ah, good point, @Pondlife! And that would be a management nightmare to create the local role in each database and populate it with all users. I suppose if you were using Windows authentication, you could use a domain group login that contains all users with rights to the SQL Server, and then give the datareader role to that login in each db. Thus, whenever a user from that group had no user-specific permissions for their login, it would fall back to the given db role.
ewall
+1  A: 

For new databases can you not just add the user/group into a read only role within the model database. When a new database is created this is used as the template.

SPE109
+1  A: 

The easiest solution is to add your user to the model database. All new databases 'inherit' from model, so if you add the user there, it will automatically be in all new ones:

use model
exec sp_adduser @Loginame = 'MyLogin', @name_in_db = 'MyUser'
exec sp_addrolemember @rolename = 'db_datareader', @membername = 'MyUser'

Note that this only works if you actually execute CREATE DATABASE. If you create new databases by restoring a backup (or CREATE then RESTORE) then the contents of the backup will overwrite whatever comes from model.

If your needs are more complex, write your own script or tool to create new databases, and just put the logic in there. You might want to do this anyway if you have to manage a large number of databases.

Pondlife