我有一张table
CREATE TABLE items(
id SERIAL PRIMARY KEY,
group_id INT NOT NULL,
item_id INT NOT NULL,
name TEXT,
.....
.....
);
我正在创建一个函数
1.获取单个group_id
的行值集,如果输入行中存在多个group_id
,则失败
1.将其与表中的匹配值进行比较(仅适用于group_id
1.更新更改的值(仅用于输入group_id
)
1.插入新值
1.删除行输入中不存在的表行(将行与group_id
和item_id
进行比较)(仅适用于输入group_id
)
这是我的函数定义
CREATE OR REPLACE FUNCTION update_items(rows_input items[]) RETURNS boolean as $$
DECLARE
rows items[];
group_id_input integer;
BEGIN
-- get single group_id from input rows, fail if multiple group_id's present in input
-- read items of that group_id in table
-- compare input rows and table rows (of the same group_id)
-- create transaction
-- delete absent rows
-- upsert
-- return success of transaction (boolean)
END;
$$ LANGUAGE plpgsql;
我正尝试在查询中调用函数
select update_items(
(38,1,1283,"Name1"),
(39,1,1471,"Name2"),
(40,1,1333,"Name3")
);
我得到以下错误Failed to run sql query: column "Name1" does not exist
- 我尝试删除
id
列值:也会产生同样的误差
将行值传递给接受表类型数组作为参数的函数的正确方法是什么?
2条答案
按热度按时间pcww981p1#
更新更改的值
插入新值删除表格行
行输入中不存在(比较具有group_id和item_id的行)
如果你想做upsert,你必须用唯一约束upsert。所以有两个唯一约束。主键(id),(group_id,item_id)。冲突插入需要考虑这两个唯一约束。
因为你想把
items[]
类型传递给函数,所以这也意味着任何不在输入函数参数中的id也会被删除。主要功能:
称之为:
参考文献:
guz6ccqo2#
如果有人想做同样的事情,下面是我如何用DELETE缺失的行实现UPSERT的。
此函数用于删除
in_rows
中缺少的行