dpcj40970 2016-05-20 12:24
浏览 74

如何检查MySQL存储函数返回空结果的原因?

DELIMITER $$
CREATE FUNCTION `monthtargetbyuser`(`userId` BIGINT,month VARCHAR(11),year VARCHAR(11)) RETURNS int(11)

BEGIN 

  DECLARE target,da BIGINT;
  set da = year-month;

  SET target = (SELECT ifnull(user_target.monthly_target,0) as monthly_target from user_target left join users on users.id=user_target.user_id where date_format(users.doj,'%Y-%m') <= 'da' and user_target.year=year and year(users.doj)>0 and users.locked !=1 and users.id =userId );  


  RETURN target;
END

While executing the MySQL query given in the function, it returns an empty result or zero rows. But while executing the stored function, it gives incorrect result, i.e, it returns a value. How do I check that the MySQL function returns an empty result?

  • 写回答

1条回答 默认 最新

  • dream12001 2016-05-20 12:34
    关注

    Some smart person will probably give a better answer but what worked for me was to add a check at the end of the function, to see if the variable was null and if it was then set it to a value such as Unknown. That way you always get a value returned from the function, even when no rows are returned from your query, eg:

      SET target = (SELECT ifnull(user_target.monthly_target,0) as monthly_target from user_target left join users on users.id=user_target.user_id where date_format(users.doj,'%Y-%m') <= 'da' and user_target.year=year and year(users.doj)>0 and users.locked !=1 and users.id =userId );  
    
      IF (target IS NULL) THEN
            SET target = "Unknown";
      END IF;
    
      RETURN target;
    
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本