Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

sql - Function to get number of weekdays between two dates excluding holidays

I have an sql query that casts 2 dates and checks if they are equal. But even though the dates are equal, i dont get the result.

create or replace 
FUNCTION getWorkingDays(
  DATE_ONE DATE,
  DATE_TWO DATE)
RETURN NUMBER
IS
DAY_COUNT  NUMBER := 0;
START_DATE DATE;
END_DATE   DATE;
HOL_COUNT NUMBER := 0;
BEGIN        
IF(DATE_ONE                   IS NOT NULL AND DATE_TWO IS NOT NULL) THEN
  IF DATE_ONE                  < DATE_TWO THEN
    START_DATE                := DATE_ONE;
    END_DATE                  := DATE_TWO;
  ELSE
    START_DATE := DATE_TWO;
    END_DATE   := DATE_ONE;
  END IF;     
  WHILE START_DATE < END_DATE       
  LOOP      
    IF TO_CHAR(START_DATE,'DY') NOT IN ('SAT','SUN') THEN
      DAY_COUNT := DAY_COUNT         + 1;
    END IF;      
     SELECT count(*) INTO HOL_COUNT
FROM ATL_JOB_HOLIDAY jh
JOIN ATL_MASTER_JOB mj
ON MJ.MASTER_JOB_ID       = JH.MASTER_JOB_ID
WHERE TRUNC(HOLIDAY_DATE) = START_DATE;
     IF(HOL_COUNT >0) THEN
      DAY_COUNT := DAY_COUNT         + 1;
       Dbms_Output.put_line('Holiday333 :- IS A HOLIDAY');
       END IF; 
        START_DATE := START_DATE + 1;       
  END LOOP;
END IF;
RETURN DAY_COUNT;
EXCEPTION
WHEN OTHERS THEN
  RETURN NULL;
END getWorkingDays;'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I am guessing that you are using Oracle. If so, the DATE data type contains a time component. This is rather confusing. But you could do what you want using TRUNC() rather than CAST():

SELECT TRUNC(HOLIDAY_DATE), DATE '2011-04-16'  --into DAY_COUNT
FROM ATL_JOB_HOLIDAY jh JOIN
     ATL_MASTER_JOB mj
     ON mj.MASTER_JOB_ID = jh.MASTER_JOB_ID
WHERE TRUNC(HOLIDAY_DATE) = DATE '2011-04-16';

Note also the preference for ANSI standard dates and for table aliases.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...