Open In App

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

Last Updated : 06 Dec, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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:




--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


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.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads