简体   繁体   中英

Using nextval to insert new data in table from temp table

I'm having issues with the following (in PostgreSQL).

Purpose:

  • read data from temp table tmp
  • process this to another table y
  • use the nextval from table y combined with data from tmp .

I thought this would do the job:

INSERT INTO y (v1, v2) VALUES (nextval(y.v1), SELECT v2 FROM tmp)

also tried:

INSERT INTO y (v1, v2) VALUES (SELECT nextval(y.v1), v2 FROM tmp)

can anyone explain how to do this?

There are two misconceptions/error in the code you have shown:

  1. nextval() expects the name of a sequence, not a column name.
  2. If a select statement is used to supply the data for an insert statement, you can't use values()

I think you want something like is:

insert into y (v1, v2) 
select nextval(...), v2 
from tmp;

It is unclear to me what you mean with " use the nextval from table y ". As already mentioned nextval() operates on sequences not on tables or columns. If you mean " take the nextval from the sequence associated with y.v1 " and y.v1 is defined as a serial column you can do something like this:

insert into y (v1, v2) 
select nextval(pg_get_serial_sequence('y','v1')), v2 
from tmp;

But this requires v1 to be defined as serial

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM