with dates as (
select distinct dte from (
select from_date, to_date+case when to_date<date'9999-12-31' then 1 else 0 end to_date from tableA
union all
select valid_from as from_date, valid_to+case when valid_to<date'9999-12-31' then 1 else 0 end as to_date from tableB
)
unpivot(dte for col in(from_date, to_date))
)
select row_number() over (order by from_date) as id, from_date, to_date-case when to_date<date'9999-12-31' then 1 else 0 end as to_date from (
select distinct dte from_date,
lead(dte) over(order by dte) to_date
from dates a
left join tableA b on a.dte between b.from_date and b.to_date
left join (select valid_from as from_date, valid_to as to_date from tableB) c on a.dte between c.from_date and c.to_date
)
where from_date is not null and to_date is not null
order by 1,2