从 postgres 插入中返回一个值,并使用它来在其他表上插入新记录



请原谅我这个问题。我是Postgres的新手,我觉得自己像个傻瓜,问我似乎是一个简单的问题。我有一个插入,我需要在两个 postgres 12 表中做。第一个返回将作为外键插入到第二个表中的 PK。问题是我在SQL上遇到错误。它不喜欢我的声明声明。我知道我一定在做傻事。SQL是我最弱的技能 任何帮助将不胜感激,这是我第一次尝试使用postgres。

现在我得到 c# 错误:23502:列"付费"中的空值违反了非空约束

为清楚起见进行编辑:我需要获取第二个插入 PK 作为返回值。

更新的代码:每个发布的答案

我更新了 GMB 的响应作为答案我的约束错误是因为我不知道我需要将序列更新为导入数据的当前最大 ID,@GMB非常感谢您的回复!!

-- FUNCTION: public."insert_totalRecord"(text,text,text,text,text,text,text,text,text,text,text,text,text,text,bigint, out integer)
-- DROP FUNCTION public."insert_totalRecord"(text,text,text,text,text,text,text,text,text,text,text,text,text,text,bigint, out integer);
CREATE OR REPLACE FUNCTION public."insert_totalRecord"(
in cc text, 
in mu text, 
in re text, 
in pc text, 
in ad text, 
in ad2 text,
in pr text, 
in gn text, 
in mn text, 
in fn text, 
in af text, 
in st text, 
in iea text, 
in pp text, 
in drid bigint,
out pid integer)
RETURNS integer
LANGUAGE 'sql'
COST 100
VOLATILE 
AS $BODY$
WITH t AS (
INSERT INTO postaladdress (
CountryCode,
Municipality,
Region,
PostalCode, 
Address1, 
Address2) 
VALUES (cc, mu, re, pc, ad, ad2) 
RETURNING paid
)
INSERT INTO personaldata (
Prefix,
GivenName, 
MiddleName, 
FamilyName, 
Affix,
DStatus, 
PostalAddressId, 
InternetEmailAddress, 
PrimaryPhone, 
DId
)
SELECT 
pr, 
gn, 
mn, 
fn, 
af, 
st, 
paid, 
iea, 
pp, 
drid
FROM t
RETURNING pid;
$BODY$;
ALTER FUNCTION public."FF_insert_totalRecord"(text,text,text,text,text,text,text,text,text,text,text,text,text,text,bigint, OUT integer)
OWNER TO postgres;

您可以在 Postgres 中的单个查询中执行此操作:

WITH t AS (
INSERT INTO postaladdress (
CountryCode,
Municipality,
Region,
PostalCode, 
Address1, 
Address2) 
VALUES (cc, mu, re, pc, ad, ad2) 
RETURNING my_new_paid
)
INSERT INTO personaldata (
Prefix,
GivenName, 
MiddleName, 
FamilyName, 
Affix,
DStatus, 
PostalAddressId, 
InternetEmailAddress, 
PrimaryPhone, 
DId
)
SELECT 
pr, 
gn, 
mn, 
fn, 
af, 
st, 
my_new_paid, 
iea, 
pp, 
drid
FROM t
RETURNING pid;

最新更新