【问题标题】:Oracle SQL dynamic date insertOracle SQL 动态日期插入
【发布时间】:2014-12-23 18:42:59
【问题描述】:

我有一个包含一些缺失数据的外汇汇率表。我有一个 from_ccy_code、to_ccy_code、fx_date 和 fx_rate 列。我要做的是 from_ccy_code = USD 和 to_ccy_code = EUR,如果该日期不存在记录,则插入一条记录(fx_rate 设置为 1)。 在这种情况下,除了要插入 fx_rate 的日期之外,所有其他值都是静态的。如果值不存在,我可以编写 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'));

任何帮助将不胜感激。

【问题讨论】:

  • 您的意思是要在单个语句中插入一个日期范围内所有缺失日期的记录吗?或者只是你想让你的固定日期成为一个参数?
  • 我想为预定义日期范围内的所有缺失日期插入一条记录。如果可能的话,我想在一个声明中理想地做到这一点。

标签: sql oracle date dynamic


【解决方案1】:

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

当然,您可以使用自己的日期范围,我只是使用固定值来演示 - 您可能真的想要绑定开始和结束日期的值,或者从当月的开始 - 使用 @987654324 @ 而不是固定的开始日期。取决于我想这将如何以及何时运行。

您可以将固定值添加到同一查询中,将其用作公共表表达式(或内联视图),并使用类似的 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.

【讨论】:

    猜你喜欢
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    相关资源
    最近更新 更多