Im trying to create a GRANT script for a DB.
The DB cannot use any built in roles, so I need to re-create db_reader, db_writer and EXEC for stored procedures into a GRANT script assigned to this service account.
I am trying to automate this, instead of looking at each item in the DB and manually creating this.
I have this so far:
/* USER_TABLE */
select 'GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.' + name + ' TO [DOMAIN\user]' from sys.objects where type = 'U' order by name;
/* INTERNAL_TABLE */
select 'GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.' + name + ' TO [DOMAIN\user]' from sys.objects where type = 'IT' order by name;
/* VIEW */
select 'GRANT SELECT ON dbo.' + name + ' TO [DOMAIN\user]' from sys.objects where type = 'V' order by name;
/* SQL_STORED_PROCEDURE */
select 'GRANT EXECUTE ON dbo.' + name + ' TO [DOMAIN\user]' from sys.objects where type = 'P' order by name;
/* SQL_TABLE_VALUED_FUNCTION */
select 'GRANT SELECT, INSERT, UPDATE, DELETE ON dbo.' + name + ' TO [DOMAIN\user]' from sys.objects where type = 'TF' order by name;
/* SQL_SCALAR_FUNCTION */
select 'GRANT EXECUTE ON dbo.' + name + ' TO [DOMAIN\user]' from sys.objects where type = 'FN' order by name;
But, I am unsure what rights all the other items need, ie: SERVICE_QUEUE, SQL_TRIGGER, etc. (see below) Also, if the above is correct.
select DISTINCT(type_desc), type as a from sys.objects WHERE type <> 'S';
— the ones I don’t believe i need
- DEFAULT_CONSTRAINT (D)
- FOREIGN_KEY_CONSTRAINT (F)
- PRIMARY_KEY_CONSTRAINT (PK)
- SERVICE_QUEUE (SQ)
- UNIQUE_CONSTRAINT (UQ)
- SQL_TRIGGER (TR)
–The ones i believe i need
- USER_TABLE (U)
- INTERNAL_TABLE (IT)
- VIEW (V)
- SQL_STORED_PROCEDURE (P)
- SQL_TABLE_VALUED_FUNCTION (TF)
- SQL_SCALAR_FUNCTION (FN)
Thanks in advance!
In my opinion you have to do the following:
Then, for each user that you want to give rights to, just do
You should avoid adding explicit permissions to objects and users. You will make your life easier when you use database roles and schemas to arrange security you need. You can have a look at my blog, there’s more about this topic.
Regards
Piotr