算一下我周末生日的场合

时间:2014-11-25 16:20:48

标签: oracle plsql

我想计算一个周末我生日的次数。

declare
v_count number;
v_birthday date := '22-07-1993';
v_sysdate date := sysdate;
begin
--1) first i have to know all the dates when it was my birthday till sysdate.
--2) then i have to convert it to a char(?) and look if its in the weekend (saturday or sunday)
--3) if yes, count have to be increased by one, if not, go to the next birthday till sysdate.
--4) show count in dbms.output_put_line(v_count);
-- ("for i_counter in 1..10 loop" and "while i_counter <=10 loop"
end;

我想我必须使用LOOP,但我只知道有数字的LOOP,而不是日期。

1 个答案:

答案 0 :(得分:1)

此代码将计算在1993年至2014年的周末(星期六或星期日)将于7月22日发生的天数:

    set serveroutput on size 100000
    declare
        V_DATE        DATE;
        I             NUMBER;
        WEEKEND_COUNT NUMBER;
    begin
        WEEKEND_COUNT := 0;
        FOR I IN 1993 .. 2014 
        LOOP
            V_DATE := TO_DATE('07/22/' || TO_CHAR(I), 'MM/DD/YYYY');
            DBMS_OUTPUT.PUT_LINE(
                'DATE: ' || V_DATE || ' ' || 
                'DAY_OF_WEEK: ' || TO_CHAR(V_DATE, 'DY'));
            IF TO_CHAR(V_DATE, 'DY') = 'SAT' OR
               TO_CHAR(V_DATE, 'DY') = 'SUN' THEN
               WEEKEND_COUNT := WEEKEND_COUNT +1;
            END IF;           

        END LOOP;

        DBMS_OUTPUT.PUT_LINE ('NUMBER OF BIRTHDAYS ON WEEKENDS: ' || 
        WEEKEND_COUNT);
    end;

输出结果为:

DATE: 22-JUL-93 DAY_OF_WEEK: THU
DATE: 22-JUL-94 DAY_OF_WEEK: FRI
DATE: 22-JUL-95 DAY_OF_WEEK: SAT
DATE: 22-JUL-96 DAY_OF_WEEK: MON
DATE: 22-JUL-97 DAY_OF_WEEK: TUE
DATE: 22-JUL-98 DAY_OF_WEEK: WED
DATE: 22-JUL-99 DAY_OF_WEEK: THU
DATE: 22-JUL-00 DAY_OF_WEEK: SAT
DATE: 22-JUL-01 DAY_OF_WEEK: SUN
DATE: 22-JUL-02 DAY_OF_WEEK: MON
DATE: 22-JUL-03 DAY_OF_WEEK: TUE
DATE: 22-JUL-04 DAY_OF_WEEK: THU
DATE: 22-JUL-05 DAY_OF_WEEK: FRI
DATE: 22-JUL-06 DAY_OF_WEEK: SAT
DATE: 22-JUL-07 DAY_OF_WEEK: SUN
DATE: 22-JUL-08 DAY_OF_WEEK: TUE
DATE: 22-JUL-09 DAY_OF_WEEK: WED
DATE: 22-JUL-10 DAY_OF_WEEK: THU
DATE: 22-JUL-11 DAY_OF_WEEK: FRI
DATE: 22-JUL-12 DAY_OF_WEEK: SUN
DATE: 22-JUL-13 DAY_OF_WEEK: MON
DATE: 22-JUL-14 DAY_OF_WEEK: TUE
NUMBER OF BIRTHDAYS ON WEEKENDS: 6