错误:语法错误在或附近" IF"

时间:2014-08-11 02:14:38

标签: sql postgresql

我在我的函数中添加了IF子句:

CREATE OR REPLACE FUNCTION get_path_set(IN pathset_id_in character,OUT id character,OUT  pathset_id character,OUT utility double precision)
RETURNS SETOF record AS
$BODY$
BEGIN
    IF EXISTS (SELECT 1 FROM "A" WHERE "ID" = $1)  THEN 
        SELECT "ID", "PATHSET_ID", "UTILITY"
        FROM "B"
        where "PATHSET_ID" = $1;
    END IF;
END;
$BODY$

  LANGUAGE sql VOLATILE
  COST 100
  ROWS 1000;

它引发了一个错误:

ERROR:  syntax error at or near "IF"
LINE 8:  IF EXISTS (SELECT 1 FROM "A" ...

我错过了什么吗?

感谢

1 个答案:

答案 0 :(得分:2)

当语言是SQL时,它需要是常规查询,因此通过移动IF子句中的WHERE条件将逻辑转换为纯SQL:

SELECT "ID", "PATHSET_ID", "UTILITY"
FROM "B"
WHERE "PATHSET_ID" = $1
AND EXISTS (SELECT 1 FROM "A" WHERE "ID" = $1)