在CTE中使用Execute语句

时间:2017-12-13 12:57:22

标签: postgresql postgresql-9.4

PREPARE insert_DEL_CRN(bigint, char, char, char) as 
insert into
deleted_crns(id, crn, ror, cpr) values($1, $2, $3, $4) 
ON CONFLICT (crn) 
DO update 
   set id=$1, ror=$3, cpr=$4;

尝试将以下CTE表达与EXECUTE insert_DEL_CRN

一起使用
WITH deleted_record as (
   delete from crns where crn='8000440000'
   RETURNING id,crn,ror,cpr
) 
execute insert_DEL_CRN 
select deleted_record.id, deleted_record.crn, deleted_record.ror,
deleted_record.cpr 
from deleted_record;

导致此错误:

ERROR:  syntax error at or near "EXECUTE"
LINE 1: ... where crn='8000440000' RETURNING id,crn,ror,cpr) EXECUTE in...

任何人都可以在此指出任何具体问题。

1 个答案:

答案 0 :(得分:1)

您需要将两个语句合并为一个。要引用DO UPDATE部分中有冲突的行的值,请使用特殊关键字excluded

WITH deleted_record as (
   delete from crns 
   where crn='8000440000'
   RETURNING id,crn,ror,cpr
) 
insert into deleted_crns (id, crn, ror, cpr)
select id,crdn,ror,cpr
FROM deleted_records
ON CONFLICT (crn) 
DO update 
   set id = excluded.id, 
       ror = excluded.ror,
       cpr = excluded.cpr;