Postgres:无法创建函数

时间:2019-02-19 09:47:40

标签: postgresql

我需要编写一个非常简单的函数。我将传递三个参数(employeeid,employeetitle和employeeaddress)。如果传递的employeeid等于0,那么将在表中插入一条新记录。如果通过的employeeid大于0,那么记录将被更新。在这两种情况下,employeeid都将作为结果返回(id是employee表中的自动增量值)。我正在使用pgAdmin,这是我编写的代码:

CREATE FUNCTION public.addupdateemployee(IN employeeid bigint, IN employeetitle text, IN employeeaddress text)
RETURNS bigint
LANGUAGE 'plpgsql'

AS $BODY$
BEGIN
DECLARE affectedrecordid bigint = 0
IF employeeid = 0 THEN
INSERT INTO employeemaster(title, address)
values(employeetitle, employeeaddress)
RETURNING id INTO affectedrecordid;
RETURN affectedrecordid;
ELSE
UPDATE employeemaster 
SET title = employeetitle,
address = employeeaddress
WHERE id = employeeid  
RETURN employeeid;
END IF
END
$BODY$;

执行上述语句时,出现以下错误:

ERROR:  syntax error at or near "IF"
LINE 8: IF employeeid = 0 THEN
        ^
SQL state: 42601
Character: 218

我无法找出问题所在。有人可以帮我修复以上功能吗?

1 个答案:

答案 0 :(得分:2)

declare必须排在第一个begin之前。并且您缺少;变量声明以及IF块之后。语言名称是一个标识符,不应放在单引号中。并且UPDATE语句需要RETURNING而不是RETURN

应该是:

CREATE FUNCTION public.addupdateemployee(IN employeeid bigint, IN employeetitle text, IN employeeaddress text)
  RETURNS bigint
  LANGUAGE plpgsql
AS $BODY$
DECLARE 
  affectedrecordid bigint = 0;
begin  
  IF employeeid = 0 THEN
    INSERT INTO employeemaster(title, address)
    values(employeetitle, employeeaddress)
    RETURNING id INTO affectedrecordid;
    RETURN affectedrecordid;
  ELSE
    UPDATE employeemaster 
      SET title = employeetitle,
        address = employeeaddress
    WHERE id = employeeid  
    RETURNING employeeid;
  END IF;
END;
$BODY$;