29

Basically, I need to query about a thousand NEXTVAL from a sequence. I can query them in a loop, or I can query them through a join with a reeeeeally big table.

Is there any less hacky way?

Upd. Basically, I have a schedule of operations on objects. Each object has either a generated UUID, or an ID from database. After I calculate an optimal schedule, I need to write it into DB, but every ID in the table HAS to be from a sequence. So I need to query some IDs from that sequence. The problem is that looping query is slow, since the DB is really far from me, and I can't just loose several seconds while executing dozens of queries in a loop. So I need to query all those new IDs in one query.

Alexis Dufrenoy
  • 11,784
  • 12
  • 82
  • 124
F0RR
  • 1,590
  • 4
  • 16
  • 30
  • Also NB that you may need/want to use a large fetchsize to avoid still having an RTT per row returned: http://stackoverflow.com/a/17331855/32453 – rogerdpack Jun 26 '13 at 22:59

4 Answers4

42

You can use this:

select your_sequence.nextval
from (
   select level 
   from dual 
   connect by level < 1000
);
27

Depends on what you want to do with them.

If you insert them in a table, you can unse seq.nexval in the insert query. (As explained here: How can I insert multiple rows into oracle with a sequence value?)

If you use them in a loop, you can fetch them in that loop.

What do you want to do with them?

As I know, you can't fetch multiple values from sequence.

UPDATE: a_horse_with_no_name's aswer can be improved like this:

select your_sequence.nextval
from dual 
connect by level < 1000

:)

Community
  • 1
  • 1
Florin Ghita
  • 17,525
  • 6
  • 57
  • 76
3

My (H2) unit test database did not support "connect by", so I had to come up with something else:

    with temp_id_table (lvl) as 
       (select 1 as lvl from dual 
        union all 
        select lvl+1 
          from temp_id_table 
          where lvl < 1000) 
    select sequence_name.nextval 
    from temp_id_table;
Thomas
  • 56
  • 2
-4
select sequence_name.nextval
from dual
connect by level < number of values you want to print;
Rob Bajorek
  • 6,382
  • 7
  • 44
  • 51