我想填充一个带有运行整数的表列,所以我想使用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中的游标迭代方法呢?
答案 0 :(得分: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);
或者您使用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
答案 1 :(得分:3)
UPDATE table_a
SET sequence_column = (select rn
from (
select rowid,
row_number() over (order by col1, col2)
from table_a
) x
where x.rowid = table_a.rowid)
但这不会很快,正如Damien指出的那样,每次更改该表中的数据时都必须重新运行此语句。
答案 2 :(得分:2)
首先创建一个序列:
CREATE SEQUENCE SEQ_SLNO
START WITH 1
MAXVALUE 999999999999999999999999999
MINVALUE 1
NOCYCLE
NOCACHE
NOORDER;
之后使用序列更新表:
UPDATE table_name
SET colun_name = SEQ_SLNO.NEXTVAL;
答案 3 :(得分:1)
小幅修正只需添加 AS RN :
}