SET SQLBLANKLINES ON;

/
-- Poblar tabla AD74A66T00
DECLARE
CURSOR CTRAM IS
    SELECT DISTINCT(EXP.ID_EXPEDIENTE_00), TRUNC(TRAM.F_REALIZACION_10) F_REALIZACION_10, TRAM.USU_MODIF_10
    FROM AD74A10T00 TRAM INNER JOIN AD74A00T00 EXP ON (TRAM.ID_EXPEDIENTE_10 = EXP.ID_EXPEDIENTE_00)
    WHERE EXP.ID_PROCEDIMIENTO_00 = '0087002'--Altas
    AND TRAM.F_REALIZACION_10 IS NOT NULL AND TRUNC(TRAM.F_REALIZACION_10) >= TO_DATE('10/01/2025', 'dd/mm/yyyy')
    AND TRAM.ID_TRAMITE_10 IN (3); --Estudios

BEGIN

    --Borrar datos previos
    DELETE FROM AD74A66T00;
    --Reiniciar la secuencia
    --EXECUTE IMMEDIATE 'CREATE SEQUENCE AD74A66T00_SEQ  MINVALUE 1 MAXVALUE 99999999 INCREMENT BY 1 START WITH 1 NOCACHE  NOORDER  NOCYCLE';
    
    FOR TRAM IN CTRAM LOOP
        INSERT INTO AD74A66T00 (ID_HISTORICO_66, USUARIO_66, FECHA_HISTORICO_66, ID_EXPEDIENTE_66) 
        VALUES(SEQ_HIST_ESTUIDO_ALTA.NEXTVAL, TRAM.USU_MODIF_10, TRAM.F_REALIZACION_10, TRAM.ID_EXPEDIENTE_00);
    END LOOP;
    
    COMMIT;
END;

/