Luk*_*man 17 sql oracle rownum sql-update
我想填充一个带有运行整数的表列,所以我想使用ROWNUM.但是,我需要根据其他列的顺序填充它,例如ORDER BY column1, column2
.遗憾的是,由于Oracle不接受以下声明,因此不可能:
UPDATE table_a SET sequence_column = rownum ORDER BY column1, column2;
Run Code Online (Sandbox Code Playgroud)
也不是以下语句(尝试使用WITH子句):
WITH tmp AS (SELECT * FROM table_a ORDER BY column1, column2)
UPDATE tmp SET sequence_column = rownum;
Run Code Online (Sandbox Code Playgroud)
那么如何使用SQL语句并且不依赖于PL/SQL中的游标迭代方法呢?
Luk*_*der 28
这应该工作(适合我)
update table_a outer
set sequence_column = (
select rnum from (
-- evaluate row_number() for all rows ordered by your columns
-- BEFORE updating those values into table_a
select id, row_number() over (order by column1, column2) rnum
from table_a) inner
-- join on the primary key to be sure you'll only get one value
-- for rnum
where inner.id = outer.id);
Run Code Online (Sandbox Code Playgroud)
或者您使用该MERGE
声明.像这样的东西.
merge into table_a u
using (
select id, row_number() over (order by column1, column2) rnum
from table_a
) s
on (u.id = s.id)
when matched then update set u.sequence_column = s.rnum
Run Code Online (Sandbox Code Playgroud)