Oracle 11g - FOR loop that inserts only weekdays into a table?

浪尽此生 提交于 2019-12-10 17:48:39

问题


I want to insert some data into a table associated with dates for the next year. I actually only need workdays inserted.

 BEGIN
  FOR i IN 1..365 LOOP
  INSERT INTO MY_TABLE (ID, MY_DATE)
  VALUES (i, (to_date(sysdate,'DD-MON-YY')-1)+i);
  END LOOP;
 END;

I can solve my problem by going back and deleting rows that are weekend days, but that seems rather inelegant - can anyone think of a way to modify my loop so that it skips weekends?


回答1:


You could always check the day of the week before inserting the row (the names of the days of the week will depend on your NLS settings so this isn't the most robust solution possible)

 BEGIN
  FOR i IN 1..365 LOOP
    IF( to_char(sysdate-1+i,'fmDAY') NOT IN ('SATURDAY', 'SUNDAY') )
    THEN
      INSERT INTO MY_TABLE (ID, MY_DATE)
        VALUES (i, (to_date(sysdate,'DD-MON-YY')-1)+i);
    END IF;
  END LOOP;
 END;



回答2:


I would suggest using to_date(your_date,'d') as @Jeff Moore mentions. However, I'd also suggest getting rid of the for..loop. As a bonus, this will add all days of any given year, unlike your version, which will generate an extra day on leap years:

INSERT INTO MY_TABLE (ID, MY_DATE)
SELECT   lvl, dt
  FROM   (    SELECT   LEVEL lvl,
                       TO_DATE('1/1/2011', 'mm/dd/yyyy') + LEVEL - 1 dt
                FROM   DUAL
          CONNECT BY   TO_DATE('1/1/2011', 'mm/dd/yyyy') + LEVEL - 1 <
                          ADD_MONTHS(TO_DATE('1/1/2011', 'mm/dd/yyyy'), 12))
 WHERE   TO_CHAR(dt, 'd') NOT IN (1, 7)

If you want your "ID" column to be contiguous, you can use rownum instead of lvl in the outer query.




回答3:


You can use one of the following date formats to check which day it is.

select to_char(sysdate,'DAY') from dual; /* TUESDAY */
select to_char(sysdate,'D') from dual; /* 3 */
select to_char(sysdate,'DY') from dual; /* TUE */

Add the if statement as shown below to remove days that equal SAT or SUN.

BEGIN
  FOR i IN 1..365 LOOP
  IF to_char(sysdate-1+i,'DY') NOT in ('SAT','SUN') THEN

   INSERT INTO MY_TABLE (ID, MY_DATE) VALUES (i, (to_date(sysdate,'DD-MON-YY')-1)+i);
  END IF;
 END LOOP;
END;



回答4:


If you let Monday = 0 and Sunday = 6 you could use (if mod(i,7) < 4 )) then Insert... should work.



来源:https://stackoverflow.com/questions/6587501/oracle-11g-for-loop-that-inserts-only-weekdays-into-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!