Oracle:结合使用 ROWNUM 和 ORDER BY 子句更新表列
我想用连续的整数填充表列,所以我考虑使用 ROWNUM。但是,我需要根据其他列的顺序填充它,例如 ORDER BY column1, column2
。不幸的是,这是不可能的,因为 Oracle 不接受以下语句:
UPDATE table_a SET sequence_column = rownum ORDER BY column1, column2;
也不接受以下语句(尝试使用WITH子句):
WITH tmp AS (SELECT * FROM table_a ORDER BY column1, column2)
UPDATE tmp SET sequence_column = rownum;
那么我如何使用 SQL 语句而不诉诸 PL/SQL 中的游标迭代方法来做到这一点?
I want to populate a table column with a running integer number, so I'm thinking of using ROWNUM. However, I need to populate it based on the order of other columns, something like ORDER BY column1, column2
. That is, unfortunately, not possible since Oracle does not accept the following statement:
UPDATE table_a SET sequence_column = rownum ORDER BY column1, column2;
Nor the following statement (an attempt to use WITH clause):
WITH tmp AS (SELECT * FROM table_a ORDER BY column1, column2)
UPDATE tmp SET sequence_column = rownum;
So how do I do it using an SQL statement and without resorting to cursor iteration method in PL/SQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这应该有效(对我有效)
或者您使用 MERGE 语句。像这样的东西。
This should work (works for me)
OR you use the
MERGE
statement. Something like this.但这不会很快,正如 Damien 指出的那样,每次更改该表中的数据时都必须重新运行此语句。
But that won't be very fast and as Damien pointed out, you have to re-run this statement each time you change data in that table.
首先创建一个序列:
然后使用序列更新表:
First Create a sequence :
after that Update the table using the sequence:
一个小修正只需添加 AS RN :
A small correction just add AS RN :