Postgresql不会从if语句返回显示查询结果

时间:2016-12-08 17:11:26

标签: postgresql function if-statement

这是我运行的查询,并且已成功执行。但是postgresql只显示" CREATE FUNCTION - 查询在265毫秒内成功返回。"

-- For every order that has been received, display the order ID, the total dollar amount owed on that order
-- (you’ll have to calculate this total from attributes in one or more tables; label this result TotalDue), and 
-- the amount received in payments on that order (assume that there is only one payment made on each 
-- order). To make this query a little simpler, you don’t have to include those orders for which nopayment 
-- has yet been received. List the results in decreasing order of the difference between total due and amount paid.


CREATE OR REPLACE FUNCTION fun() RETURNS text AS $$
DECLARE result1 text;
BEGIN
    IF  (SELECT pay.paymentamount 
        FROM order_t o JOIN orderline_t ol ON o.orderid = ol.orderid
        LEFT JOIN payment_t pay ON pay.orderid = o.orderid
        JOIN product_t pr ON pr.productid = ol.productid
        WHERE orderedquantity > 0
        GROUP BY o.orderid, pay.paymentamount) != NULL
    THEN
        SELECT o.orderid, sum(ol.orderedquantity * pr.productstandardprice) AS total_due, pay.paymentamount, 
        sum(ol.orderedquantity * pr.productstandardprice) - paymentamount AS total_owed
        INTO result1
        FROM order_t o
        JOIN orderline_t ol ON o.orderid = ol.orderid
        LEFT JOIN payment_t pay ON pay.orderid = o.orderid
        JOIN product_t pr ON pr.productid = ol.productid
        WHERE orderedquantity > 0
        GROUP BY o.orderid, pay.paymentamount
        ORDER BY o.orderid;
    ELSE    
        SELECT o.orderid, sum(ol.orderedquantity * pr.productstandardprice) AS total_due, pay.paymentamount, 
        sum(ol.orderedquantity * pr.productstandardprice) AS total_owed
        INTO result1
        FROM order_t o
        JOIN orderline_t ol ON o.orderid = ol.orderid
        LEFT JOIN payment_t pay ON pay.orderid = o.orderid
        JOIN product_t pr ON pr.productid = ol.productid
        WHERE orderedquantity > 0
        GROUP BY o.orderid, pay.paymentamount
        ORDER BY o.orderid;
    END IF;
    RETURN result1;
END;
$$ LANGUAGE plpgsql;

对于未在payment_t表中记录付款的订单,我继续将total_owed设置为total_due。

1 个答案:

答案 0 :(得分:0)

您已创建了自己的功能,但尚未运行! PostgreSQL Documentation有很多关于如何在运行后调用函数的示例。我对它并不熟悉,但看起来你可以简单地运行SELECT fun()