ALTER TABLE TBCASO_TIPO
    ADD PAINEL_ID INTEGER;

ALTER TABLE TBCASO_ORIGEM
    ADD MOTIVO_ID INTEGER,
    ADD PAINEL_ID INTEGER;
	
ALTER TABLE TBCASO_SQL
    ADD PAINEL_ID INTEGER;

/***********************************************************************/

UPDATE TBCASO_TIPO A
    SET A.PAINEL_ID = COALESCE((SELECT FIRST 1 B.PAINEL_ID FROM TBCASO_MOTIVO B WHERE B.ID = A.MOTIVO_ID), 0)
    WHERE A.PAINEL_ID IS NULL;

UPDATE TBCASO_ORIGEM A
    SET A.MOTIVO_ID = COALESCE((SELECT FIRST 1 B.MOTIVO_ID FROM TBCASO_TIPO B WHERE B.ID = A.TIPO_ID), 0),
        A.PAINEL_ID = COALESCE((SELECT FIRST 1 B.PAINEL_ID FROM TBCASO_TIPO B WHERE B.ID = A.TIPO_ID), 0)
    WHERE A.PAINEL_ID IS NULL;
	
UPDATE TBCASO_SQL A
    SET A.PAINEL_ID = COALESCE((SELECT FIRST 1
                                    X.PAINEL_ID
                        
                                FROM (
                                    SELECT
                                        'CASO' AS TIPO,
                                    
                                        B.ID,
                                        B.ID AS PAINEL_ID,
                                        B.SQL_EMAIL_CONTATO AS SQL_ID
                                    
                                    FROM TBCASO_PAINEL B
                            
                                    UNION ALL
                                    
                                    SELECT
                                        'CAMPO' AS TIPO,
                                    
                                        C.ID,
                                        C.PAINEL_ID,
                                        C.SQL_ID
                                    
                                    FROM TBCASO_CAMPO_CONSULTA C
                                ) X
                                WHERE X.SQL_ID = A.ID
                            ), 0)
    WHERE A.PAINEL_ID IS NULL;

/***********************************************************************/

CREATE INDEX ITBCASO_TIPO_03
ON TBCASO_TIPO (PAINEL_ID);

CREATE INDEX ITBCASO_ORIGEM_03
ON TBCASO_ORIGEM (MOTIVO_ID);

CREATE INDEX ITBCASO_ORIGEM_04
ON TBCASO_ORIGEM (PAINEL_ID);

CREATE INDEX ITBCASO_SQL_01
ON TBCASO_SQL (PAINEL_ID);

/***********************************************************************/
/***********************************************************************/

