MYSQL自定义函数之返回两个时间的指定类型时差

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

DELIMITER $$

CREATE FUNCTION DateBetween
  (AType INT, ADateStart DATETIME, ADateEnd DATETIME)
RETURNS BIGINT
BEGIN
DECLARE AResult BIGINT DEFAULT -1;
/*入参AType INT类型,结果类型 1:年 2:月 3:日 4:小时 5:分钟 6:秒钟 (必须在1-6内,否则结果返回-1)
*入参ADateStart DATETIME类型,起始时间 (必须是一个正确的日期参数)
*入参ADateEnd DATETIME类型,结束时间 (必须是一个正确的日期参数)
*返回值 BIGINT类型,返回起始之间与结束时间的指定时差 (成功返回计算出的时差,失败返回-1)
*/
IF ADateStart != '' AND ADateEnd != '' AND AType >=1 AND AType <= 6 THEN
  CASE AType
  WHEN 1 THEN
    SELECT TIMESTAMPDIFF(YEAR, ADateStart, ADateEnd) INTO AResult; 
  WHEN 2 THEN 
    SELECT TIMESTAMPDIFF(MONTH, ADateStart, ADateEnd) INTO AResult;   
  WHEN 3 THEN
    SELECT TIMESTAMPDIFF(DAY, ADateStart, ADateEnd) INTO AResult; 
  WHEN 4 THEN
    SELECT TIMESTAMPDIFF(HOUR, ADateStart, ADateEnd) INTO AResult; 
  WHEN 5 THEN
    SELECT TIMESTAMPDIFF(MINUTE, ADateStart, ADateEnd) INTO AResult; 
  WHEN 6 THEN
    SELECT TIMESTAMPDIFF(SECOND, ADateStart, ADateEnd) INTO AResult; 
  END CASE;
END IF;
RETURN(AResult); 
END$$