现在我的问题是我想在事务中进行批量插入并获取所有生成的密钥.
我用RETURNING和CURRVAL得到的是最后生成的id,结果的其余部分被丢弃.
我怎样才能让它归还所有这些?
谢谢
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;