Wednesday, May 23, 2018

Get max value in partition

Set serverout on size 1000000
declare
    cursor tab_part_cur IS
      select table_name,partition_name from user_tab_partitions where table_name='MESSAGE_LOG' order by 1,2;
    v_date date;
    v_pass integer := 0;
begin
    dbms_output.put_line('These partitions can be dropped.');
    for tab_part_rec in tab_part_cur
    loop
        exit when tab_part_cur%notfound;
        v_date := GET_MAX_LOG_TS(tab_part_rec.table_name,tab_part_rec.partition_name);
        if v_date <= (sysdate - 10) then
           dbms_output.put_line(tab_part_rec.table_name||' '||tab_part_rec.partition_name|| ' '||v_date );
        end if;
    end loop;
end;
/




CREATE  or replace FUNCTION GET_MAX_LOG_TS (
    p_TableName     IN VARCHAR2,
    p_PatitionName  IN VARCHAR2
) RETURN DATE
IS
   v_DateVal Date;
   v_string varchar2(400);
BEGIN      
       v_string := 'SELECT max(log_ts)  v_DateVal FROM MESSAGE_LOG PARTITION('||p_PatitionName||')';

dbms_output.put_line(v_string);
dbms_output.put_line(chr(10));
execute immediate v_string into into v_DateVal;;

    RETURN v_DateVal;
END GET_max_log_ts;
/