我试图在我的数据库上运行商店程序/功能,该程序/功能显示所有具有礼品清单的用户< 5.我在IF"或附近收到错误"语法错误。 我已单独运行SQL语句,并且工作正常。
--function counts the number of giftlists per user
--and put their names into a new table
CREATE OR REPLACE FUNCTION foo()
RETURNS TABLE(users_id users.users_id%TYPE, first_name users.first_name%TYPE, last_name users.last_name%TYPE) AS
$func$
BEGIN
-- if number of giftlists < 5
IF(SELECT gift_lists.users_id, COUNT (gift_lists.gift_lists_id) as number_giftlists < 5 FROM gift_lists LEFT JOIN users ON gift_lists.users_id =
users.users_id GROUP BY gift_lists.users_id)
RETURN QUERY
SELECT v.users_id, v.first_name, v.last_name
FROM my_view v;
ELSE
RETURN QUERY
SELECT v.users_id, v.first_name, v.last_name
FROM my_view v;
END IF;
END
$func$ LANGUAGE sql STABLE;
答案 0 :(得分:1)
您不能在标准SQL或PostgreSQL的SQL方言中使用顶级IF
。
Use CASE .. WHEN ... THEN ... END
代替,或使用PL / PgSQL语言。 PL / PgSQL允许您使用IF
语句。
另外,这个:
COUNT (gift_lists.gift_lists_id) as number_giftlists < 5
毫无意义。我想你的意思是:
SELECT
gift_lists.users_id,
COUNT (gift_lists.gift_lists_id) as number_giftlists
FROM gift_lists
LEFT JOIN users ON gift_lists.users_id = users.users_id
GROUP BY gift_lists.users_id
HAVING COUNT (gift_lists.gift_lists_id) < 5