Trouble with Oracle Connect By and Date Ranges -
let's have table data ranges
create table ranges (id number, date_from date, date_to date); insert ranges values (1, to_date('01.01.2017', 'dd.mm.rrrr'), to_date('03.01.2017', 'dd.mm.rrrr')); insert ranges values (2, to_date('05.02.2017', 'dd.mm.rrrr'), to_date('08.02.2017', 'dd.mm.rrrr')); and output should 1 row every date in these ranges
id | the_date ---------------- 1 | 01.01.2017 1 | 02.01.2017 1 | 03.01.2017 2 | 05.02.2017 2 | 06.02.2017 2 | 07.02.2017 2 | 08.02.2017 but connect gives me ora-01436 connect loop
select connect_by_root(id), trunc(date_from, 'dd') + level - 1 the_date ranges connect prior id = id , trunc(date_from, 'dd') + level - 1 <= trunc(date_to, 'dd') order id, the_date what's wrong?
you can add call non-deterministic function, e.g.
and prior dbms_random.value not null so becomes:
select connect_by_root(id), trunc(date_from, 'dd') + level - 1 the_date ranges connect prior id = id , prior dbms_random.value not null , trunc(date_from, 'dd') + level - 1 <= trunc(date_to, 'dd') order id, the_date; connect_by_root(id) the_date ------------------- --------- 1 01-jan-17 1 02-jan-17 1 03-jan-17 2 05-feb-17 2 06-feb-17 2 07-feb-17 2 08-feb-17 7 rows selected. there's explanation of why necessary in oracle community post; uses sys_guid() instead of dbms_random.value, principle same.
if you're on 11gr2 or higher use recursive subquery factoring instead:
with rcte (root_id, the_date, date_to) ( select id, date_from, date_to ranges union select root_id, the_date + 1, date_to rcte the_date < date_to ) select root_id, the_date rcte order root_id, the_date; root_id the_date ---------- --------- 1 01-jan-17 1 02-jan-17 1 03-jan-17 2 05-feb-17 2 06-feb-17 2 07-feb-17 2 08-feb-17 7 rows selected.
Comments
Post a Comment