首先,你的JSON格式有誤,我猜意爲:
[
{"EMP_ID":1,"NAME":"Y","VECH_NO":4587,"SALARY":1500},
{"EMP_ID":3,"NAME":"Z","VECH_NO":4007,"SALARY":1800}
]
假設如下表定義:
CREATE TEMP TABLE employee_details(
"EMP_ID" integer primary key,
"NAME" text,
"VECH_NO" integer,
"SALARY" numeric
);
而且一個樣本數據(只顯示更新):
INSERT INTO employee_details VALUES(1, 'X', 123, 123);
您可以先使用json_array_elements
to make each array one row and json_populate_record
to get each value as the original table type,像這樣:
SELECT r.*
FROM
json_array_elements('[{"EMP_ID":1,"NAME":"Y","VECH_NO":4587,"SALARY":1500},{"EMP_ID":3,"NAME":"Z","VECH_NO":4007,"SALARY":1800}]') AS a(element),
json_populate_record(NULL::employee_details, a.element) AS r;
有了這一點,你可以簡單的使用INSERT ... ON CONFLICT UPDATE
:
INSERT INTO employee_details("EMP_ID", "NAME", "VECH_NO", "SALARY")
(
SELECT r."EMP_ID", r."NAME", r."VECH_NO", r."SALARY"
FROM
json_array_elements('[{"EMP_ID":1,"NAME":"Y","VECH_NO":4587,"SALARY":1500},{"EMP_ID":3,"NAME":"Z","VECH_NO":4007,"SALARY":1800}]') AS a(element),
json_populate_record(NULL::employee_details, a.element) AS r
)
ON CONFLICT ("EMP_ID") DO
UPDATE SET
"NAME" = EXCLUDED."NAME",
"VECH_NO" = EXCLUDED."VECH_NO",
"SALARY" = EXCLUDED."SALARY"
;
的ON CONFLICT
條款僅適用於9.5或更高版本。在此之前,您必須使用some tricks with loop and retry或可寫公用表表達式(儘管存在競爭條件問題);無論如何,如果你使用的是舊版本,那麼這是一個很好的理由。
目前尚不清楚你正在嘗試做什麼。 – redneb
我有一個JSON數組。我必須更新如果存在,否則使用任何inbuild函數(如「json_populate_recordset」)插入它。 – user3410249
似乎你在你的例子中交換了'[]'和'{}'。你使用的是什麼版本的PostgreSQL?如果在9.5之前,你能升級(使用新的upsert功能)嗎? – MatheusOl