Grant SQL Login db_owner when new database gets created

Hello Guys,

I have a doubt regarding granting database level roles to the created SQL Login on the newly created databases in our environment. Is it somehow possible to automate this?? Meaning my requirement is to grant the SQL login a database role (db_owner, db_datawriter, etc) to databases as soon as they are created.
As per my knowledge there are two ways:
1. Making changes to model: Not preferred since this will affect all the other databases as well.
2. Using DDL Trigger: This I prefer since we have certain naming conventions in our environment and this rule should be applied only to them.
Doing some research on the internet, I found this piece of code:

CREATE TRIGGER trg_DDL_CreateDatabase
ON ALL SERVER
FOR CREATE_DATABASE
AS
DECLARE @databaseName sysname;
SET @databaseName = (SELECT EVENTDATA().value('(/EVENT_INSTANCE/DatabaseName)[1]', 'sysname'));
declare @sql nvarchar(max);
set @sql = N'USE ' + quotename(@databaseName) + N';
IF IS_MEMBER (''DOMAIN\GROUP'') = 1
EXEC sp_addrolemember N''db_owner'', N''DOMAIN\SOMEGROUP''
ELSE
EXEC sp_addrolemember N''db_owner'', N''DOMAIN\SOMEOTHERGROUP'';';
exec sp_executesql @sql;

Open in new window


I did not try this since I want to add naming constraint to this query. I'm not well versed with triggers concept. Kindly help me on this and give your suggestions.
Eldo issacAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Deepak ChauhanSQL Server DBACommented:
Above script will also apply on all new datbases because there is no check for naming conventions.

I have modified the above and added two more variables. Change when you test the script.
Set @User ='Test'  --- This is for user name or group which you want to add.
Set @namingConv='DB_%'  -- This is for database naming conventions like db name start with "DB_"
Create TRIGGER trg_DDL_CreateDatabase
ON ALL SERVER
FOR CREATE_DATABASE
AS
DECLARE @databaseName sysname;
Declare @User nvarchar(100);
Declare @namingConv varchar(50);
Set @User ='Test'
Set @namingConv='DB_%'
SET @databaseName = (SELECT EVENTDATA().value('(/EVENT_INSTANCE/DatabaseName)[1]', 'sysname'));
declare @sql nvarchar(max)

IF @databaseName like @namingConv
Begin
set @sql = N'USE ' + quotename(@databaseName) + CHAR(13)+CHAR(10)+N'
create user '+'['+@User+'] '+  'for login '+'['+@User+']'+CHAR(13)+CHAR(10) +
'EXEC sp_addrolemember N''db_owner'', N'''+@User+''''+CHAR(13)+CHAR(10)+
'print  ''user added in the database'''
END
ELSE 
Print 'Databaes  '+@databaseName +'  name does not match the naming convention or Login does not exist to add the user'
Exec sp_executesql @sql

Open in new window

0
Scott PletcherSenior DBACommented:
Change the bold areas to match your specific data:

CREATE TRIGGER trg_DDL_CreateDatabase
ON ALL SERVER
AFTER CREATE_DATABASE
AS
DECLARE @databaseName varchar(128);
SET @databaseName = (SELECT EVENTDATA().value('(/EVENT_INSTANCE/DatabaseName)[1]', 'sysname'));
IF @databaseName LIKE '%<matching_db_name_pattern>%'
BEGIN
      DECLARE @sql_template varchar(8000);
      DECLARE @sql varchar(8000)
      SET @sql_template = 'USE [$db$]; ' +
            'IF NOT EXISTS(SELECT 1 FROM sys.database_principals dp WHERE dp.name = ''$user$'') ' +
            '    CREATE USER [$user$] FROM LOGIN [$user$]; ' +
            'EXEC sp_addrolemember ''db_owner'', ''$user$'' '
      SET @sql = REPLACE(REPLACE(@sql, '$db$', @databaseName), '$user$', '<add_your_user_name_here>')
      EXEC (@sql)
END --IF
GO --end of trigger
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.