微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

postgresql – 从Posgtres批量插入返回多个SERIAL值

我正在使用Postgres,使用SERIAL作为我的主键.插入一行后,我可以使用’RETURNING’或CURRVAL()来获取生成的键.

现在我的问题是我想在事务中进行批量插入并获取所有生成的密钥.

我用RETURNING和CURRVAL得到的是最后生成的id,结果的其余部分被丢弃.

我怎样才能让它归还所有这些?

谢谢

您可以将RETURNING与多个值一起使用:
psql=> create table t (id serial not null,x varchar not null);
psql=> insert into t (x) values ('a'),('b'),('c') returning id;
 id 
----
  1
  2
  3
(3 rows)

所以你想要更像这样的东西:

INSERT INTO AutoKeyEntity (Name,Description,EntityKey) VALUES
('AutoKey 254e3c64-485e-42a4-b1cf-d2e1e629df6a','Testing 5/4/2011 8:59:43 AM',DEFAULT)
returning EntityKey;
INSERT INTO AutoKeyEntityListed (EntityKey,Listed,ItemIndex) VALUES
(CURRVAL('autokeyentity_entityKey_seq'),'Test 1 AutoKey 254e3c64-485e-42a4-b1cf-d2e1e629df6a',0),(CURRVAL('autokeyentity_entityKey_seq'),'Test 2 AutoKey 254e3c64-485e-42a4-b1cf-d2e1e629df6a',1),'Test 3 AutoKey 254e3c64-485e-42a4-b1cf-d2e1e629df6a',2)
returning EntityKey;
-- etc.

然后,您必须从事务中的每个语句中收集返回的EntityKey值.

你可以尝试在事务的开始和结束时获取序列的当前值,并使用它们来确定使用了哪些序列值但是that is not reliable

Furthermore,although multiple sessions are guaranteed to allocate
distinct sequence values,the values might be generated out of
sequence when all the sessions are considered. For example,with a
cache setting of 10,session A might reserve values 1..10 and return
nextval=1,then session B might reserve values 11..20 and return
nextval=11 before session A has generated nextval=2. Thus,with a
cache setting of one it is safe to assume that nextval values are
generated sequentially; with a cache setting greater than one you
should only assume that the nextval values are all distinct,not
that they are generated purely sequentially. Also,last_value will
reflect the latest value reserved by any session,whether or not
it has yet been returned by nextval.

因此,即使您的序列的缓存值为1,您仍可在事务中使用非连续的序列值.但是,如果序列的缓存值与事务中INSERT的数量相匹配,那么您可能会安全,但我猜这会太大而无法理解.

更新:我刚刚注意到(感谢提问者的评论),涉及两个表,在文本墙中有点丢失.

在这种情况下,您应该能够使用当前的INSERTS:

INSERT INTO AutoKeyEntity (Name,2);
-- etc.

并从AutoEntityKey上的INSERT一次获取一个EntityKey值.可能需要某种脚本来处理RETURNING值.您还可以在函数中包装AutoKeyEntity和相关的AutoKeyEntityListed INSERT,然后使用INTO获取EntityKey值并从函数返回:

INSERT INTO AutoKeyEntity /*...*/ RETURNING EntityKey INTO ek;
/* AutoKeyEntityListed INSERTs ... */
RETURN ek;

原文地址:https://www.jb51.cc/postgresql/191883.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐