Update Oracle table column with row number

2019-04-08 22:57发布

I want to update a table column with row number. Each row in empid column should update with related row number. I tried following query.

UPDATE employee SET empid = row_number();

But this is not working. Any idea?

4条回答
做个烂人
2楼-- · 2019-04-08 23:28

you could also do this

create table your_table_name as
select row_number() over( order by 1) as serial_no, a.* from your_query a

this creates the serial number when you write the table itself. ( note this is not set as PK if you want it to act as pk)

查看更多
霸刀☆藐视天下
3楼-- · 2019-04-08 23:32

You could do something like the following. You can change the ORDER BY order the rows if needed.

UPDATE emp
SET empid = emp.RowNum
FROM (SELECT empid, ROW_NUMBER() OVER (ORDER BY empid) AS rowNum FROM employee) emp
查看更多
够拽才男人
4楼-- · 2019-04-08 23:39

UPDATE employee SET empid = row_number();

Firstly, it is syntactically incorrect.

Secondly, you cannot use ROW_NUMBER() analytic function without the analytic_clause.

As you replied to my comment that the order doesn't matter to you, you could simply use ROWNUM.

UPDATE employee SET empid = ROWNUM;

It will assign the pseudo-column value by randomly picking the rows. Since you are assigning EMPID, I would suggest you should consider ordering.

Usually employee ids are generated using a SEQUENCE object. There are two ways to implement the auto-increment functionality:

查看更多
老娘就宠你
5楼-- · 2019-04-08 23:40

First, this is not the correct syntax for the row_number() function, since you're missing the over clause (resulting in an ORA-30484 error). Even if it was, this would not work, as you cannot directly use window functions in a set clause (resulting in an ORA-30483 error).

For this usecase, however, you could just use the rownum pseudo-column:

UPDATE employee SET empid = ROWNUM;

SQLFiddle

查看更多
登录 后发表回答