0
我一直試圖在2個給定日期之間得到週末天數(週六和週日)。返回週末天的MySQL函數
我碰到這樣的解決方案:http://crossedlogic.blogspot.ca/2008/09/using-sql-to-find-work-days-in-date.html
當我調用該函數,它返回作爲輸出消息OK,我想它返回的週末兩天的計數來代替。
我在做什麼錯?
代碼:
DROP FUNCTION IF EXISTS `fn_GET_WEEKEND_DAYS`;
DELIMITER $$
CREATE FUNCTION `fn_GET_WEEKEND_DAYS`(StartDate DATE, EndDate DATE) RETURNS INT
BEGIN
# declare the variables.
DECLARE varDays INT;
# create the temprorary table to insert the data in.
CREATE TEMPORARY TABLE temp(calendarDate DATE, isWeekend TINYINT(1));
# insert the starting date.
INSERT INTO temp VALUES(StartDate, NULL);
# insert each day by increment of 1 day untill reached the end date.
WHILE (SELECT MAX(CalendarDate) FROM temp) < EndDate DO
INSERT INTO temp
SELECT ADDDATE(MAX(CalendarDate), INTERVAL 1 DAY), NULL
FROM temp;
END WHILE;
# update the is weekend field depending if the day of week of each row is 1 or 7. (saturday or sunday)
UPDATE temp SET isWeekend = CASE WHEN DAYOFWEEK(calendarDate) IN (1, 7) THEN true ELSE false END;
# count the date that are weekends.
SELECT COUNT(calendarDate) INTO varDays FROM temp WHERE isWeekend = true;
# drop the temp table.
DROP TEMPORARY TABLE IF EXISTS temp;
RETURN varDays;
END $$
TEST:
SELECT fn_GET_WEEKEND_DAYS(CURDATE(), ADDDATE(CURDATE(), INTERVAL 10 DAY)) AS TEST;
任何幫助和建議將不勝感激。
不是問題,但有一個問題是您在UPDATE語句中有一個misspelt列名。被認爲應該是週末。此外,DAYOFWEEK會返回1至7. – Kickstart
謝謝您指出。 – Sam