PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Restituzione di più valori SERIAL dall'inserimento batch di Posgtres

Puoi utilizzare RETURNING con più valori:

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)

Quindi vuoi qualcosa di più simile a questo:

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),
(CURRVAL('autokeyentity_entityKey_seq'),'Test 3 AutoKey 254e3c64-485e-42a4-b1cf-d2e1e629df6a', 2)
returning EntityKey;
-- etc.

E poi dovrai raccogliere la EntityKey restituita valori di ogni estratto conto nella transazione.

Potresti provare a prendere il valore corrente della sequenza all'inizio e alla fine della transazione e usarli per capire quali valori di sequenza sono stati usati ma non è affidabile :

Quindi, anche se le tue sequenze hanno cache valori di uno è ancora possibile avere valori di sequenza non contigui nella transazione. Tuttavia, potresti essere al sicuro se la cache della sequenza il valore corrisponde al numero di INSERT nella transazione, ma suppongo che sarà troppo grande per avere un senso.

AGGIORNAMENTO :Ho appena notato (grazie ai commenti dell'interrogante) che ci sono due tabelle coinvolte, un po' perse nel muro di testo.

In tal caso, dovresti essere in grado di utilizzare gli INSERTI correnti:

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),
(CURRVAL('autokeyentity_entityKey_seq'),'Test 3 AutoKey 254e3c64-485e-42a4-b1cf-d2e1e629df6a', 2);
-- etc.

E prendi la EntityKey valori uno alla volta dagli INSERT su AutoEntityKey . Potrebbe essere necessaria una sorta di script per gestire i valori RETURNING. Puoi anche avvolgere AutoKeyEntity e relativo AutoKeyEntityListed INSERT in una funzione, quindi utilizzare INTO per prendere la EntityKey valore e restituirlo dalla funzione:

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