欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mysql函数-计算两个月份之间的月份 mysql函数两个日期之间的月份 

程序员文章站 2022-05-28 12:58:30
...
CREATE  FUNCTION `months_between`(`big_date` date,`small_date` date) RETURNS int(11)
BEGIN
	 declare diffMonth int;
   declare diffYear int;
   declare diffDay int;
   declare number int;

  select month(big_date)-month(small_date) ,day(big_date)-day(small_date) ,year(big_date)-year(small_date) into diffMonth,diffDay,diffYear;


if diffMonth > 0 and diffDay >= -1 then
   set number=diffYear*12 + diffMonth;
elseif diffMonth > 0 and  diffDay < -1 then
		 set number=diffYear*12 + diffMonth-1;
elseif diffMonth < 0 and  diffDay > -1 then 
    set number=diffYear*12 - (month(small_date)-month(big_date))+1;
elseif diffMonth = 0 and diffDay >= -1 then
    set number=diffYear*12 ;
else 
    set number = diffYear*12 - (month(small_date)-month(big_date));
end if;

return number;

END