Massive insert sql - Oracle 11g

时间:2016-02-23 01:41:01

标签: sql oracle datetime

我需要一个查询,以便在今天的最后N天内将行插入到表中。

Insert into Table select 'xpto', name 
from users where login_date between 
    TO_DATE(:DATE || ' 00:00:00', 'mm/dd/yyyy HH24:MI:SS') 
and TO_DATE(:DATE || ' 23:59:59', 'mm/dd/yyyy HH24:MI:SS')

我需要在过去30天内代表:DATE ...(每天).. 所以这将是30个插入。

我该怎么做?

修改

假设我想插入过去30天的数据......所以我们有:

01/18/2016
01/19/2016
01/20/2016
...
02/01/2016
02/02/2016
02/03/2016
....
02/15/2016
....
02/22/2016

我希望单个查询 - 或声明 - 根据上面的每一天插入我的数据,如下所示:

Insert into Table select 'xpto', name 
from users where login_date between 
    TO_DATE('01/15/2016' || ' 00:00:00', 'mm/dd/yyyy HH24:MI:SS') 
and TO_DATE('01/15/2016' || ' 23:59:59', 'mm/dd/yyyy HH24:MI:SS')
--- another insert
Insert into Table select 'xpto', name 
from users where login_date between 
    TO_DATE('01/16/2016' || ' 00:00:00', 'mm/dd/yyyy HH24:MI:SS') 
and TO_DATE('01/16/2016' || ' 23:59:59', 'mm/dd/yyyy HH24:MI:SS')

我不想每天都进行一次查询...

另一个编辑

对不起,我刚拿到笔记本电脑......这是真实的样本:

BEGIN
for day in (SELECT to_char(TO_DATE (SYSDATE, 'dd/mm/yyyy')-30 + LEVEL) AS DATE_CHECK
      FROM DUAL
CONNECT BY SYSDATE - 30 + LEVEL <= SYSDATE)
  LOOP
  v_date := to_char(day.date_check);
  INSERT INTO resume (date_check, type, total)
SELECT   v_data AS DATA, type, COUNT (*) total
    FROM ( select ....
 from table
 WHERE DATE_COLUMN BETWEEN TO_DATE(v_data ||' 00:00:00', 'dd/mm/yyyy hh24:mi:ss') and TO_DATE(v_date || ' 23:59:59', 'dd/mm/yyyy hh24:mi:ss')
union 
select ....
 from table
 WHERE DATE_COLUMN BETWEEN TO_DATE(v_data ||' 00:00:00', 'dd/mm/yyyy hh24:mi:ss') and TO_DATE(v_date || ' 23:59:59', 'dd/mm/yyyy hh24:mi:ss')
)

end loop;
end;

但它不起作用...如果我按照任何日期(2016年2月14日)手动替换v_date进行相同的插入,它可以工作....

:(

1 个答案:

答案 0 :(得分:2)

如果我理解您正在尝试正确执行的操作,则可能会有以下情况:

Insert into Table
  select 'xpto', name 
    from users
    where login_date between TRUNC(SYSDATE) - INTERVAL '30' DAY
                         and TRUNC(SYSDATE) + INTERVAL '1' DAY - INTERVAL '1' SECOND

修改

根据问题的编辑,我们可以扩展范围,如:

Insert into Table
  select 'xpto', name 
    from users
    where login_date between TO_DATE('01/18/2016', 'MM/DD/YYYY') 
                         and TO_DATE('02/22/2016', 'MM/DD/YYYY') + INTERVAL '1' DAY - INTERVAL '1' SECOND

第二次编辑

谢谢你的澄清。也许以下内容会有所帮助:

BEGIN
  for day in (SELECT TRUNC(SYSDATE)-30 + LEVEL AS DATE_CHECK
                FROM DUAL
                CONNECT BY TRUNC(SYSDATE) - 30 + LEVEL <= TRUNC(SYSDATE))
  LOOP
    INSERT INTO resume (date_check, type, total)
      SELECT day.DATE_CHECK AS DATA, type, COUNT (*) total
        FROM (select ....
                from table
                WHERE DATE_COLUMN = TRUNC(day.DATE_CHECK));
  end loop;
end;

祝你好运。