我遇到了Postgresql函数的问题。 我想声明一个函数,它将向表中插入一行,然后返回给我这一行(但是有一个自动创建的字段,如Id)。
CREATE OR REPLACE FUNCTION UserCreate(
name character varying(80),
surname character varying(80),
age int,
email character varying(80)
)
RETURNS "Users" AS $$
BEGIN
INSERT INTO "Users"
(name,surname,age,email) VALUES
(name, surname, age, email) RETURNING
* AS result;
END;
$$ LANGUAGE 'plpgsql'
但是当我尝试创建此功能时,我收到错误:
Function's final statement must be SELECT or INSERT/UPDATE/DELETE RETURNING.
我试图在RETURNING
子句中找到一些示例,但所有示例都只使用整数等基本返回类型。
答案 0 :(得分:1)
您可以使用变量在insert ... returning
和return
之间发送结果。类似的东西:
CREATE OR REPLACE FUNCTION UserCreate(
name character varying(80),
surname character varying(80),
age int,
email character varying(80)
)
RETURNS "Users" AS $$
DECLARE
result "Users";
BEGIN
INSERT INTO "Users"
(name,surname,age,email)
VALUES (name, surname, age, email)
RETURNING * INTO result;
RETURN result;
END;
$$ LANGUAGE 'plpgsql';