0

我正在编写一个应该返回浮点值的函数。

BEGIN


DECLARE due_amount DECIMAL(9,2);
  SET due_amount = (SELECT due_amount FROM (
                SELECT id,  MAX(date), due_amount, user_id
                FROM lunch_transaction
                GROUP BY user_id
                HAVING user_id = user) l);
  IF due_amount IS NULL THEN
    SET due_amount = 0.00;
  END IF;
  RETURN due_amount;
END

该函数仅返回值0.00,即使该值应该是其他值。

仅运行此查询:

(SELECT due_amount FROM (
            SELECT id,  MAX(date), due_amount, user_id
            FROM lunch_transaction
            GROUP BY user_id
            HAVING user_id = user) l);

虽然给出了正确的输出。

我应该如何将查询的输出设置为变量?

4

1 回答 1

0

使用可能与列名冲突的变量名是非常糟糕的做法。此外,子查询似乎非常不必要。我会尝试更像这样的东西:

BEGIN
    DECLARE v_due_amount DECIMAL(9,2);

    SELECT v_due_amount := l.due_amount
    FROM lunch_transaction l
    WHERE l.user_id = in_user;  -- I'm guessing `user` is also a parameter

    IF v_due_amount IS NULL THEN
        SET v_due_amount = 0.00;
    END IF;
    RETURN v_due_amount;
END;

您的版本在子查询中有一个聚合函数。这是没有意义的,因为due_amount它不是聚合函数的参数。这个逻辑也许应该是:

    SELECT v_due_amount := SUM(l.due_amount)
    FROM lunch_transaction l
    WHERE l.user_id = in_user;  -- I'm guessing `user` is also a variable
于 2018-05-28T11:17:19.220 回答