1

So I have an application that automatically creates a new database after the database it is currently in reaches a fixed number of rows. I need to be able to automatically assign a user within the installation the db_datareader role for the automatically created database. I'm kind of at a loss here, any help is greatly appreciated.

asked Jan 21, 2014 at 16:34
1
  • 1
    If you creating databases grammatically why not add GRANT ACCESS to those scripts? Commented Jan 21, 2014 at 16:42

2 Answers 2

0

Add the user to the DB_READER role. Like this:

use YourNewDb
go
exec sp_addrolemember db_datareader, UserName (or) [domain\netusername] (or) suser_sname()
go

Copied from https://stackoverflow.com/questions/456346/t-sql-to-grant-db-datareader-and-db-datawriter

answered Jan 21, 2014 at 18:40
1
  • This is what I would like to do, but I really have no way of setting up an automated way to know when the new DB is created, or it's name without looking. I already have a script set up that does this, but I'm looking for a way to do it automatically if at all possible. Thanks for the code though! Commented Jan 22, 2014 at 16:09
3

You can do this by granting the permission in the Model database. This database is used to create any new ones.

USE model
GO
CREATE USER UserName FROM LOGIN LoginName
GO
EXEC sp_addrolemember 'db_datareader','UserName'
GO

That way, as the application creates new databases (which are copied from Model), they will already have the User and the role membership.

However be warned. This will be the case for ANY new database created with the CREATE DATABASE command on this instance. So if you create a database for a different application it will already have this user and the user will have db_datareader. Databases created with ATTACH DATABASE or RESTORE DATABASE will not use the model database, and will not copy the security from the Model database.

answered Jan 22, 2014 at 18:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.