我想创建一个接受输入参数的函数,如下所示:
[
{
"id": 1,
"organization_name": "Test Solutions",
"website": "[www..test.solutions]",
"contact_person": "John Doe"
}
]
我可以在pgadminIII中更新简单查询中的记录,它没有给我任何错误但除了JPA中的函数之外没有其他方法可以使用此查询,这将在查询中获取输入。以下是我的更新查询:
UPDATE organization p
SET (organization_name,emails,contacts,relation_type_id,website,cst_no,vat_tin_no,contact_person)=
(COALESCE(ab.organization_name, p.organization_name)
,COALESCE(ab.website, p.website)
,COALESCE(ab.contact_person, p.contact_person)
)
FROM (
select * from json_populate_recordset
(null::organization,'[{"id":1,"organization_name":"Test Solutions","website":"[www..test.solutions]","contact_person":"John Doe"}]')
) ab
WHERE p.id = ab.id;
如何在JPA中创建一个函数,它将通过传递JSON来实现,如上所示:
我尝试了一个函数,它给出了我传递参数的错误。 以下是函数语法:
CREATE OR REPLACE FUNCTION cloudschema.org_bulk_edit_json(IN j json)RETURNS SETOF record AS
$BODY$
BEGIN
UPDATE cloudschema.organization p
SET (organization_name,emails,contacts,relation_type_id,website,cst_no,vat_tin_no,contact_person)=
(COALESCE(ab.organization_name, p.organization_name)
,COALESCE(ab.website, p.website)
,COALESCE(ab.contact_person, p.contact_person)
)
FROM (
select * from json_populate_recordset
(null::cloudschema.organization,$1)
) ab
WHERE p.id = ab.id;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
ROWS 1000;
答案 0 :(得分:1)
您的查询(和函数)无法工作,因为列数与值的数量不匹配。此外,该函数不返回任何内容,因此应将其声明为RETURNS void
。
CREATE OR REPLACE FUNCTION cloudschema.org_bulk_edit_json(IN j json)
RETURNS void AS
$BODY$
BEGIN
UPDATE cloudschema.organization p
SET (organization_name, website, contact_person) =
(
COALESCE(ab.organization_name, p.organization_name),
COALESCE(ab.website, p.website),
COALESCE(ab.contact_person, p.contact_person)
)
FROM json_populate_recordset(null::cloudschema.organization,$1) ab
WHERE p.id = ab.id;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;
如果您想更新更多列,请在SET
中添加适当的值,例如:
SET (organization_name, emails, contacts, website, contact_person) =
(
COALESCE(ab.organization_name, p.organization_name),
COALESCE(ab.emails, p.emails),
COALESCE(ab.contacts, p.contacts),
COALESCE(ab.website, p.website),
COALESCE(ab.contact_person, p.contact_person)
)