DECLARE @tpl NVARCHAR(MAX)
  = N'
SET DEADLOCK_PRIORITY LOW /* to avoid killing client transaction */
ALTER DATABASE [@db@]
SET COMPATIBILITY_LEVEL = 160;
';

--begin transaction;
--set xact_abort on;

/* declare variables */
DECLARE @db VARCHAR(100);
DECLARE @query NVARCHAR(MAX) = N'';

DECLARE csr_dbs CURSOR FAST_FORWARD READ_ONLY FOR
SELECT [d].[name]
  FROM [sys].[databases] d
 WHERE [d].[is_read_only]        = 0
   AND [d].[state_desc]          = 'online'
   AND [d].[source_database_id] IS NULL
   AND [d].[compatibility_level] <> 160;

OPEN csr_dbs;

FETCH NEXT FROM csr_dbs
 INTO @db;

WHILE @@FETCH_STATUS = 0
BEGIN
  SET @query = REPLACE(@tpl, '@db@', @db);
  PRINT @query;
  raiserror('Applying setting on %s',0,0,@db) with nowait;
  exec(@query);
  raiserror('done',0,0,@db) with nowait;
  raiserror('-----',0,0,@db) with nowait;

  FETCH NEXT FROM csr_dbs
   INTO @db;
END

CLOSE csr_dbs;
DEALLOCATE csr_dbs;

--rollback transaction;
