Basics about assigning variables in PL/pgSQL:
Apart from that, your function has a number of syntax errors and other problems. Starting with:
CREATE OR REPLACE FUNCTION "freeTicket" (eid integer NOT NULL)
DECLARE ...
The function would work like this:
CREATE OR REPLACE FUNCTION free_ticket(_eid integer, OUT _row_ct int) AS
$func$
DECLARE
coupon_code text; -- semicolon required
BEGIN
INSERT INTO purchases (cid, pdate, eid, ccode)
SELECT cid, now()::date, _eid
, (SELECT code FROM couponCode WHERE eid = _eid AND percentage = 100)
FROM purchase
GROUP BY cid
HAVING COUNT(*) > 5 -- count(*) is faster
ORDER BY cid; -- ORDER BY is *not* pointless.
GET DIAGNOSTICS _row_ct := ROW_COUNT;
END
$func$ LANGUAGE plpgsql;
The added OUT row_ct int
is returned at the end of the function automatically. It obviates the need for an explicit RETURNS
declaration.
You also had a table alias in:
INSERT INTO purchases p (cid, pdate, eid, ccode)
But INSERT
statements require the AS
keyword for aliases to avoid ambiguity (unlike other DML statements). So: INSERT INTO purchases AS p ...
. But no need for an alias since there is no ambiguity in the statement.
Related:
Asides: Two tables named purchase
and purchases
, that's bound to lead to confusion. And the second table might also be replaced with a VIEW
or MATERIALIZED VIEW
.