我创建了此功能,可以检查航班的总费用是否已正确计算。它应该乘以座位的价格,例如400乘以客户要求的座位数,例如2.如果客户正确输入总数,例如,它应该成功返回查询。如果他们没有正确输入总数,例如1000然后它应该提出例外'价格已被错误地计算'。
CREATE FUNCTION check_totalcost() RETURNS trigger AS $check_totalcost$
DECLARE seatprice int;
DECLARE noofseats int;
BEGIN
SELECT priceperseat INTO seatprice
FROM flight
WHERE flightid = flightid;
SELECT numseats INTO noofseats
FROM flightbooking
WHERE flightid = flightid;
IF(seatprice*noofseats != new.totalcost) THEN
RAISE EXCEPTION 'price has been calculated incorrectly';
END IF;
RETURN NEW;
END;
$check_totalcost$ LANGUAGE plpgsql;
/* This is used to run the function above */
CREATE TRIGGER insert_totalcost
BEFORE INSERT OR UPDATE ON flightbooking
FOR EACH ROW EXECUTE PROCEDURE check_totalcost();
当我错误地输入总数时,它会引发我想要的异常,但是当我正确输入总数时,它也会在应该成功返回查询时引发异常。
答案 0 :(得分:0)
查询
SELECT priceperseat INTO seatprice
FROM flight
WHERE flightid = flightid;
SELECT numseats INTO noofseats
FROM flightbooking
WHERE flightid = flightid;
没有意义,因为条件总是正确的。
我想你想从插入/更新的记录中获取flightid
。使用特殊记录NEW
:
WHERE flightid = NEW.flightid;
您的函数中还有一个逻辑错误。座位数也应从new
记录中获得。
CREATE OR REPLACE FUNCTION check_totalcost()
RETURNS trigger AS $check_totalcost$
DECLARE seatprice int;
BEGIN
SELECT priceperseat INTO seatprice
FROM flight
WHERE flightid = new.flightid;
IF seatprice * new.numseats != new.totalcost THEN
RAISE EXCEPTION 'price has been calculated incorrectly';
END IF;
RETURN NEW;
END;
$check_totalcost$ LANGUAGE plpgsql;