SQL 在一个语句中从序列中查询多个 NEXTVAL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8292199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Query several NEXTVAL from sequence in one statement
提问by F0RR
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.
基本上,我需要从一个序列中查询大约一千个 NEXTVAL。我可以循环查询它们,或者我可以通过与一个非常大的表的连接来查询它们。
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.
更新。基本上,我有一个对象操作计划。每个对象都有一个生成的 UUID 或来自数据库的 ID。在我计算出一个最佳时间表后,我需要将它写入数据库,但表中的每个 ID 都必须来自一个序列。所以我需要从该序列中查询一些 ID。问题是循环查询很慢,因为数据库离我真的很远,而且我不能在循环中执行几十个查询时浪费几秒钟。所以我需要在一个查询中查询所有这些新 ID。
回答by a_horse_with_no_name
You can use this:
你可以使用这个:
select your_sequence.nextval
from (
select level
from dual
connect by level < 1000
);
回答by Florin Ghita
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?)
如果将它们插入表中,则可以在插入查询中取消 seq.nexval。(如此处所述:如何将多行插入到带有序列值的 oracle 中?)
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:
更新:a_horse_with_no_name 的答案可以这样改进:
select your_sequence.nextval
from dual
connect by level < 1000
:)
:)
回答by Thomas
My (H2) unit test database did not support "connect by", so I had to come up with something else:
我的(H2)单元测试数据库不支持“connect by”,所以我不得不想出其他办法:
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;
回答by user4096547
select sequence_name.nextval
from dual
connect by level < number of values you want to print;