用mysql写一个函数,参数有年份,月份,该月第几周,求该周的起止日期。起止日期只能包含本月日期
时间: 2024-06-02 19:14:24 浏览: 80
DELIMITER //
CREATE FUNCTION `get_week_date`(year INT, month INT, week INT)
RETURNS VARCHAR(255)
BEGIN
DECLARE week_start DATE;
DECLARE week_end DATE;
SET week_start = ADDDATE(LAST_DAY(DATE(CONCAT(year, '-', month, '-01'))), INTERVAL 1 DAY) - INTERVAL WEEKDAY(LAST_DAY(DATE(CONCAT(year, '-', month, '-01')))) DAY + INTERVAL (week - 1) * 7 DAY;
SET week_end = ADDDATE(week_start, INTERVAL 6 DAY);
IF MONTH(week_start) <> month THEN
SET week_start = NULL;
SET week_end = NULL;
ELSEIF MONTH(week_end) <> month THEN
SET week_end = ADDDATE(LAST_DAY(DATE(CONCAT(year, '-', month, '-01'))), INTERVAL 1 DAY) - INTERVAL 1 DAY;
END IF;
RETURN CONCAT(DATE_FORMAT(week_start, '%Y-%m-%d'), ' - ', DATE_FORMAT(week_end, '%Y-%m-%d'));
END//
DELIMITER ;
-- 使用示例
SELECT get_week_date(2022, 9, 2); -- 返回 '2022-09-04 - 2022-09-10'
SELECT get_week_date(2022, 9, 5); -- 返回 'NULL - NULL'
阅读全文