1
votes

I am trying to alter database through a DDL trigger which will fire on creation. However I am getting a below error.

CREATE TRIGGER ddl_trig_database 
ON ALL SERVER 
FOR CREATE_DATABASE 
AS 
    declare @dbname as nvarchar(100)
    declare @sql as nvarchar(max)

    select @dbname = 
        CAST(eventdata().query(
        '/EVENT_INSTANCE/DatabaseName[1]/text()'
        ) as NVarchar(128))
    select @sql = N'SET IMPLICIT_TRANSACTIONS OFF
    ALTER DATABASE ' + @dbname+ N' SET COMPATIBILITY_LEVEL = 110
    SET IMPLICIT_TRANSACTIONS ON'
    exec  (@sql)
GO
create database test

Error:

Msg 226, Level 16, State 6, Line 22
ALTER DATABASE statement not allowed within multi-statement transaction. The statement has been terminated.

I am on SQL Server 2014 on Windows 2012.

2

2 Answers

1
votes

If you want a specific compatibility level for each new database created - just set that compatibility level in the model database which is the "template" for all new databases being created ...

No need for a system-level trigger for this ....

1
votes

I realized the DDL trigger will be on its own transaction and Alter is not allowed if a transaction is already started. So to workaround with this problem I have created SQL Job. and put the Alters in the Job and modified the Trigger to call msdb..start_sql_job.

--Trigger
CREATE TRIGGER ddl_trig_database 
ON ALL SERVER 
FOR CREATE_DATABASE 
AS 
    exec msdb..sp_start_job 'Initialize Database'   
GO

--Job
declare @dbname as nvarchar(100)
declare @sql as nvarchar(max)
select top 1 @dbname =  name from sys.databases 
    where name like 'gtp%' and create_date >= getdate()  - .08
    order by create_date desc
IF @dbname is not null
begin
    select @sql = N'ALTER DATABASE ' + @dbname+ N' SET COMPATIBILITY_LEVEL = 110'
    exec sp_executesql @sql
    print 'Altered database'
end
print 'completed'