在 INSERT SELECT 语句期间生成增量数字列值
我需要将一些数据从 Oracle 中的一个表复制到另一个表,同时为新表中的数字列生成增量值。这是一次一次性练习,行数很少 (100)。
我对这个问题有一个足够的解决方案,但我很想知道是否有更优雅的方法。
我正在使用临时序列来完成此操作,如下所示:
CREATE SEQUENCE temp_seq
START WITH 1;
INSERT INTO new_table (new_col, copied_col1, copied_col2)
SELECT temp_seq.NEXTVAL, o.*
FROM (SELECT old_col1, old_col2
FROM old_table,
ORDER BY old_col1) o;
DROP SEQUENCE temp_seq;
有没有办法在不创建序列或任何其他临时对象的情况下进行处理? 具体来说,这可以通过独立的 INSERT SELECT 语句来完成吗?
请考虑将触发器视为不可选项。
更多信息:我想控制新行的插入顺序,并且它不会与旧表中创建的顺序相同(注意我已经添加了 ORDER BY 子句多于)。但我仍然希望我的新连续专栏从 1 开始。
也有类似的问题,但我相信我的问题的具体细节是 SO 原创的。
I need to copy some data from one table to another in Oracle, while generating incremental values for a numeric column in the new table. This is a once-only exercise with a trivial number of rows (100).
I have an adequate solution to this problem but I'm curious to know if there is a more elegant way.
I'm doing it with a temporary sequence, like so:
CREATE SEQUENCE temp_seq
START WITH 1;
INSERT INTO new_table (new_col, copied_col1, copied_col2)
SELECT temp_seq.NEXTVAL, o.*
FROM (SELECT old_col1, old_col2
FROM old_table,
ORDER BY old_col1) o;
DROP SEQUENCE temp_seq;
Is there way to do with without creating the sequence or any other temporary object? Specifically, can this be done with a self-contained INSERT SELECT statement?
Please consider a trigger to be a non-option.
MORE INFO: I would like to control the order that the new rows are inserted, and it won't be the same order they were created in the old table (note I've added the ORDER BY clause above). But I still want my new sequential column to start from 1.
There are similar questions, but I believe the specifics of my question are original to SO.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
ROWNUM
。该伪列对结果中的行进行编号:如果您希望对记录进行排序,则需要使用子查询:
You can use
ROWNUM
. This pseudo-column numbers the rows in your result:If you want your records to be sorted, you need to use a sub-query:
为什么不将 new_col 列定义为 Primary_key 或 unique 并将其标记为自动增量?
这样,每个插入都会获得下一个更高的“计数”。
我对 Oracle 不太熟悉,但我敢打赌有一个内置的自动增量函数。
Why don't you define the column new_col as primary_key or unique and mark it as autoincrement?
This way each insert will get the next higher "count".
I'm not pretty familiar with oracle, but i would bet there is a built in autoincrement function.