【原創】MySQL裡求給定的時間是所在月份的第幾個禮拜

來源:互聯網
上載者:User

Share 一個昨天寫的函數。 目的是求給定的時間是所在月份的第幾個禮拜。


DELIMITER $$USE `t_girl`$$DROP FUNCTION IF EXISTS `weekofmonth`$$CREATE DEFINER=`root`@`localhost` FUNCTION `weekofmonth`(    f_datetime DATETIME    ) RETURNS INT(11)BEGIN   -- Created by ytt.    DECLARE v_result INT;       DECLARE v_weekno INT;    SET v_weekno =    CASE DAYOFWEEK(f_datetime)    WHEN 1 THEN 7    WHEN 2 THEN 1    WHEN 3 THEN 2    WHEN 4 THEN 3    WHEN 5 THEN 4    WHEN 6 THEN 5    WHEN 7 THEN 6    END;    SET v_result = CEIL(DAYOFMONTH(DATE_SUB(f_datetime,INTERVAL v_weekno DAY))/7)+1;    RETURN v_result;    END$$DELIMITER ;



示範下結果:


SELECT weekofmonth(NOW()) AS result;


query result:


result

4


本文出自 “上帝,咱們不見不散!” 部落格,請務必保留此出處http://yueliangdao0608.blog.51cto.com/397025/1225905

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.