现在我的问题是我想在事务中进行批量插入并获取所有生成的密钥.
我用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 thatnextval
values are
generated sequentially; with a cache setting greater than one you
should only assume that thenextval
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 bynextval
.
因此,即使您的序列的缓存值为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;总结
以上是内存溢出为你收集整理的postgresql – 从Posgtres批量插入返回多个SERIAL值全部内容,希望文章能够帮你解决postgresql – 从Posgtres批量插入返回多个SERIAL值所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)