2014-10-28 119 views
0

我有一個外匯匯率表有一些缺失的數據表。我有一個from_ccy_code,to_ccy_code,fx_date和fx_rate列。我想要做的是from_ccy_code = USD和to_ccy_code = EUR,如果該日期不存在記錄,那麼插入一條記錄(fx_rate設置爲1)。 在這種情況下,除插入fx_rate的日期外,其他所有值都是靜態的。如果該值不存在,我可以編寫SQL來插入特定的日期,但我需要在插入時使日期變爲動態。有人可以幫助你解決這個問題嗎?Oracle SQL動態日期插入

以下是我到目前爲止。我知道這可能不是正確的語法,但一旦正確,這應該適用於設定日期。我不知道如何在這樣的場景中使日期變得動態。

insert into fx_rates (from_ccy_code, to_ccy_code, fx_date, fx_rate) 
select 'USD', 'EUR' 
from dual 
where not exists(select * 
       from fx_rates 
       where (from_ccy_code ='USD' and to_ccy_code ='EUR' and fx_date = '01-OCT-14')); 

任何幫助將不勝感激。

+0

你的意思是你想要在單個語句中爲日期範圍內的所有缺失日期插入記錄嗎?或者只是你想讓你的固定日期成爲一個參數? – 2014-10-28 11:36:08

+0

我想從預定義的日期範圍插入所有缺失日期的記錄。如果可能的話,我希望在一個聲明中理想地做到這一點。 – user2519487 2014-10-28 11:39:24

回答

0

您可以使用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