Count the number of a special day between two dates by using PL/SQL

Prerequisite – PL/SQL Introduction, Decision Making in PL/SQL

Write a pl/sql program to input two dates and print number of Sundays between those two dates.

Explanation:
Before each iteration of the loop, condition is evaluated. If it evaluates to TRUE, sequence_of_statements is executed. If condition evaluates to FALSE or NULL, the loop is finished and control resumes after the END LOOP statements.



Note:
The only difference between simple loop and while loop is simple execute first and then it will check condition, so simple loop execute at least once and in while loop first it will check condition and then execute.

Example-1:

Input: Enter value for date1: 01-SEP-19 
      Enter value for date2: 29-SEP-19

Output: no of Sundays : 5 

Example-2:

Input: Enter value for date1: 01-SEP-19
      Enter value for date2: 15-SEP-19

Output: no of Sundays: 3 

Code:

filter_none

edit
close

play_arrow

link
brightness_4
code

--declare the variables D1 and D2.
--type of variable is Date.
SQL> DECLARE
        D1 Date;
        D2 Date;
        Cnt Number:=0;
    BEGIN 
        D1:='&Date1';
        D2:='&Date2';
        D1:=next_day(D1-1, 'SUNDAY');
   --check the condition by using while loop.
        while(D1<=D2)
    LOOP
        Cnt:=Cnt+1;
        D1:=D1+7;
    END LOOP;
        dbms_output.put_line('no of Sundays:'||Cnt);
    END;
    /
--end of program

chevron_right


Output:

Enter value for date1: 01-SEP-19
old 5: Begin D1:='&Date1';
new 5: Begin D1:='01-SEP-19';

Enter value for date2: 29-SEP-19
old   6:  D2:='&Date2';
new   6:  D2:='29-SEP-19';
no of Sundays:5 

PL/SQL procedure successfully completed.

Advantages:-
By using while loop first it checks condition and then execute, So We count easily the number of a special day between two dates.



My Personal Notes arrow_drop_up

I Drink but I Know Things

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.