USE HCITools

IF NOT EXISTS(SELECT 1 FROM sys.[schemas] s WHERE s.[name]='delphix')
BEGIN 
    EXEC('CREATE SCHEMA [delphix]');
END 
GO

IF OBJECT_ID('delphix.change_tracking_mgmt') IS NOT NULL 
BEGIN
    DROP PROCEDURE delphix.change_tracking_mgmt;
END
GO

/*
TPDT-535

This procedure is used by Delphix to disable change tracking on every tables of a given db and schema

This is a wrapper around [hciTools].[dbo].[DBA_Change_Tracking_Maintenance] that refuses to enable maintenance mode on all tables directly.
*/
CREATE PROCEDURE delphix.change_tracking_mgmt
    @schema_name VARCHAR(100) = 'dbo'
    ,@maintenance_enabled BIT = 1
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @database_name VARCHAR(100) = 'Arizona';
    DECLARE @sqlQuery VARCHAR(MAX)='';
    DECLARE @tplGetTables VARCHAR(MAX) ='
INSERT INTO #tblList([database], [schema_name], [table_name])
SELECT ''@db@'' as Database_name, s.name AS Schema_name, t.name AS Table_name 
FROM @db@.sys.change_tracking_tables ctt
JOIN @db@.sys.tables t 
    ON t.object_id = ctt.object_id
JOIN @db@.sys.schemas s
    ON s.schema_id = t.schema_id
WHERE s.name = ''@schema@''
ORDER BY s.name, t.name;
';
    
    --fetch a list of tables with change tracking in the specified db and schema
    IF OBJECT_ID('tempdb..#tblList')IS NOT NULL BEGIN;
        DROP TABLE #tblList;
    END;

    CREATE TABLE #tblList (
        [database] VARCHAR(100) NOT NULL
        ,[schema_name] VARCHAR(100) NOT NULL 
        ,[table_name] VARCHAR(100) NOT NULL 
    );

    SELECT @sqlQuery = REPLACE(REPLACE(@tplGetTables, '@db@', @database_name), '@schema@', @schema_name);
    PRINT @sqlQuery;
    EXEC(@sqlQuery);

    SET @sqlQuery = '';

    SELECT @sqlQuery = @sqlQuery +'EXEC [arizona].[dbo].[DBA_Change_Tracking_Maintenance] @in_tableName = N'''+l.[table_name]+''', @in_maintMode = '+CAST(@maintenance_enabled AS CHAR(1))+';'+CHAR(13)+CHAR(10)
    FROM [#tblList] l
    
    PRINT @sqlQuery;
    EXEC(@sqlQuery);
END 
GO

EXEC [HCITools].[delphix].[change_tracking_mgmt] @schema_name = 'wkl', @maintenance_enabled = 0;
