Oracle过程在多列中更改日期

时间:2018-05-21 08:44:43

标签: oracle plsql procedure

尝试创建一个在结束日期小于sysdate时更改日期的过程,但它会更改所有日期,因此以下是代码:

CREATE OR REPLACE PROCEDURE CHANGE_DATES 
as 

BEGIN
    FOR rec IN (SELECT start_period_date,end_period_date FROM mytable) LOOP
    DBMS_OUTPUT.PUT_LINE('Old Date:' || rec.start_period_date ||' ' || rec.end_period_date);
    IF rec.end_period_date < sysdate THEN
        update mytable set start_period_date = sysdate;
        update mytable set end_period_date = sysdate + 6;
        commit;
        --DBMS_OUTPUT.PUT_LINE('New Date:' || begin_date ||' ' ||end_date);
    end if;
END LOOP;
END;

1 个答案:

答案 0 :(得分:1)

您需要一个WHERE子句(并且您可以在一个UPDATE语句中完成所有操作):

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE mytable ( start_period_date, end_period_date ) AS
SELECT DATE '2018-01-01', DATE '2018-01-02' FROM DUAL
/

CREATE OR REPLACE PROCEDURE CHANGE_DATES 
AS
  start_dates SYS.ODCIDATELIST;
  end_dates   SYS.ODCIDATELIST;
BEGIN
  UPDATE ( SELECT m.*,
                  ( SELECT m.start_period_date FROM DUAL ) AS old_start_date,
                  ( SELECT m.end_period_date   FROM DUAL ) AS old_end_date
           FROM mytable m )
  SET   start_period_date = SYSDATE,
        end_period_date   = SYSDATE + INTERVAL '6' DAY
  WHERE end_period_date   < SYSDATE
  RETURNING old_start_date, old_end_date
  BULK COLLECT INTO start_dates, end_dates;

  FOR i IN 1 .. start_dates.COUNT LOOP
    DBMS_OUTPUT.PUT_LINE( 'Old Date:' || start_dates(i) ||' ' || end_dates(i) );
  END LOOP;

  -- Do not COMMIT in the procedure, COMMIT in the calling scope.
END;
/

查询1

BEGIN
  CHANGE_DATES;
  COMMIT;
END;

查询2

SELECT * FROM mytable

<强> Results

|    START_PERIOD_DATE |      END_PERIOD_DATE |
|----------------------|----------------------|
| 2018-05-21T09:06:05Z | 2018-05-27T09:06:05Z |