How to get affected row count of table inside wCTE-based upsert in postgresql?

寵の児 提交于 2019-12-11 03:17:34

问题


i need your help,

I have a query with n times loop operation of insert and update.

I decided to use 'UPSERT', since it doesn’t require loop operation.

ex:

WITH upsert AS 
(UPDATE employee_table 
SET rollno=input_rollno,
name=input_name 
RETURNING *)
INSERT INTO  employee_table (rollno, name) 
SELECT 'input_rollno',input_name 
from employee_table 
WHERE NOT EXISTS (SELECT * FROM upsert);

The query is working fine and now the problem is, i want the affected row counts of individual insert and update..

i tried adding 'GET DIAGNOSTICS' after update but the query fails. i can take row count only after ending upsert.

When i added get diagnostics rowcount after update i got error: ex:

-- THIS IS WRONG. It's an EXAMPLE.

declre
num_rows INTEGER :=0;
num_rows1 INTEGER :=0;

WITH upsert AS 
(UPDATE employee_table 
SET rollno=input_rollno,
name=input_name 
RETURNING *)
GET DIAGNOSTICS num_rows = ROW_COUNT

INSERT INTO  employee_table (rollno, name) 
SELECT 'input_rollno',input_name 
from employee_table 
WHERE NOT EXISTS (SELECT * FROM upsert);
GET DIAGNOSTICS num_rows1 = ROW_COUNT;

i need to know how many rows got effected while updating and how many while inserting...

Using PostgreSQL 9.3

来源:https://stackoverflow.com/questions/32847267/how-to-get-affected-row-count-of-table-inside-wcte-based-upsert-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!