﻿DECLARE @sql nvarchar(max)

EXEC sp_changedbowner 'sa';

IF (SELECT is_broker_enabled FROM sys.databases WHERE database_id = DB_ID()) = 0 BEGIN
  SET @sql = N'ALTER DATABASE ' + DB_NAME() + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE '
  EXEC master.sys.sp_executesql @sql

  -- Ha a Service Broker IDja nem egyedi
  IF EXISTS (SELECT 1 FROM sys.databases x WHERE x.service_broker_guid = (SELECT service_broker_guid FROM sys.databases d WHERE d.database_id = DB_ID()) AND x.database_id <> DB_ID()) BEGIN
    SET @sql = N'ALTER DATABASE ' + DB_NAME() + ' SET NEW_BROKER'
    EXEC master.sys.sp_executesql @sql
  END
  ELSE BEGIN
    SET @sql = N'ALTER DATABASE ' + DB_NAME() + ' SET ENABLE_BROKER'
    EXEC master.sys.sp_executesql @sql  
  END

  SET @sql = N'ALTER DATABASE ' + DB_NAME() + ' SET MULTI_USER'
  EXEC master.sys.sp_executesql @sql

END;
GO

