您可以使用connect by
子句生成範圍的所有日期;例如看到從10月1日所有天昨天:
select date '2014-10-01' + level - 1
from dual
connect by level <= trunc(sysdate) - date '2014-10-01';
DATE'2014-10-01'+LEVEL-1
------------------------
01-OCT-14
02-OCT-14
...
26-OCT-14
27-OCT-14
27 rows selected
您可以使用,當然你自己的日期範圍,我只是用固定值來證明 - 你也許真的要爲啓動綁定值和結束日期,或從當前月份開始 - 使用trunc(sysdate, 'MM')
而不是固定的開始日期。取決於我將如何以及何時運行。
您可以添加固定的值相同的查詢,使用它作爲一個公共表表達式(或在線查看),並使用類似not exists
結構來檢查,你將需要插入值:
with t (from_ccy_code, to_ccy_code, fx_date, fx_rate) as (
select 'USD', 'EUR', date '2014-10-01' + level - 1, 1
from dual
connect by level <= trunc(sysdate) - date '2014-10-01'
)
select * from t
where not exists(
select *
from fx_rates fr
where fr.from_ccy_code = t.from_ccy_code
and fr.to_ccy_code = t.to_ccy_code
and fr.fx_date = t.fx_date
);
而且可以立足,一個insert
,但它可能是更清潔,以使其適應merge
聲明:
merge into fx_rates fr
using (
select 'USD' as from_ccy_code, 'EUR' as to_ccy_code,
date '2014-10-01' + level - 1 as fx_date, 1 as fx_rate
from dual
connect by level <= trunc(sysdate) - date '2014-10-01'
) t
on (
t.from_ccy_code = fr.from_ccy_code
and t.to_ccy_code = fr.to_ccy_code
and t.fx_date = fr.fx_date
)
when not matched then
insert (from_ccy_code, to_ccy_code, fx_date, fx_rate)
values (t.from_ccy_code, t.to_ccy_code, t.fx_date, t.fx_rate);
SQL Fiddle demo。
你的意思是你想要在單個語句中爲日期範圍內的所有缺失日期插入記錄嗎?或者只是你想讓你的固定日期成爲一個參數? – 2014-10-28 11:36:08
我想從預定義的日期範圍插入所有缺失日期的記錄。如果可能的話,我希望在一個聲明中理想地做到這一點。 – user2519487 2014-10-28 11:39:24