Function to Return Number Of Specified Days Between Two Dates

Introduction

 
Basically, an SQL function is a set of SQL statements that accept input parameters, perform actions, and return the result. A function can return a single value or a table. We can’t use a function to Insert, Update, Delete records in the database tables.
 
Prerequisite
  1. Basic knowledge of Oracle SQL
In this blog, we will create a function using a simple approach that will return the number of selected days between given two input dates.
 
In the below example, we are creating a function named "F_GET_DAYS" with input parameters as V_DATE_FROM, V_DATE_TO which represents start date and enddate respectively. We are returning a number as output. We will declare a temporary variable to store to returning days i.e V_DAYS. We are going to compare selected days with the TO_CHAR function with the DY parameter.
  1. SELECT TO_CHAR(V_DATE_FROM + LEVEL-1, 'DY') WWD_DAYS FROM DUAL CONNECT BY LEVEL <= (V_DATE_TO - V_DATE_FROM +1)  
The above query returns the number of days between two dates including the start and end date. For example, if the start date is 10th September and the end date is 15th September, we will get an output as THU, FRI, SAT, SUN, MON, TUE.
  1. SELECT COUNT(*) INTO V_DAYS FROMSELECT TO_CHAR(V_DATE_FROM + LEVEL-1, 'DY') WWD_DAYS FROM DUAL CONNECT BY LEVEL <= (V_DATE_TO - V_DATE_FROM +1)) WHERE WWD_DAYS IN ('MON','WED');  
The above query returns the number of Mondays and Wednesdays present between two dates. We can specify any days of the week where the condition according to our requirements.
 
The complete code for the function is given below and in case of any error, we are returning 0 days.
  1. CREATE OR REPLACE FUNCTION F_GET_DAYS(V_DATE_FROM DATE, V_DATE_TO DATE)  
  2. RETURN NUMBER  
  3. IS  
  4. V_DAYS NUMBER;  
  5. BEGIN  
  6. SELECT COUNT(*) INTO V_DAYS FROMSELECT TO_CHAR(V_DATE_FROM + LEVEL-1, 'DY') WWD_DAYS FROM DUAL CONNECT BY LEVEL <= (V_DATE_TO - V_DATE_FROM +1)) WHERE WWD_DAYS IN ('MON','WED');  
  7. RETURN V_DAYS;  
  8. EXCEPTION  
  9. WHEN OTHERS THEN  
  10. DBMS_OUTPUT.PUT_LINE('ERROR '||SQLCODE()|| ' - ' || SQLERRM());  
  11. RETURN 0;  
  12. END F_GET_DAYS;    
For example, if we take the start date as 1st January 2020 and the end date as 10th January, then by calling the F_GET_DAYS function, we will get 6 days.
 
Function returning number of specified days between two dates