create or replace procedure PROC_26ai_query_INSIGHTS_PENDING(p_query_id in number default null)
as

begin
  for r1 in ( select query_id
              from TB_26AI_QUERY_HISTORY
              where INSIGHT_DATE is null
              and (query_id = p_query_id or p_query_id is null )
              order by REGISTER_DATE
            ) loop
    
    insert into tb_26ai_query_insight
    select * from table( FNC_26ai_query_INSIGHTS_LIST( r1.query_id ) );
    
    update TB_26AI_QUERY_HISTORY
    set INSIGHT_DATE = sysdate
    where query_id = r1.query_id ;
    
    commit;
    
  end loop;
end;
/