简体   繁体   中英

How to UPDATE column with ROW_NUMBER() in Teradata?

I'm having a table like this

Create table test1(emp_id decimal(5,0), emp_name varchar(20));

Insert into test1(2015,'XYZ');
Insert into test1(2016,'XYZ2');

Now I want to update emp_id to row_number() or add new column into same table like (emp_no integer) to row_number().

can anyone please tell me the query for this?

You need to use UPDATE FROM:

UPDATE test1
FROM
 ( SELECT ROW_NUMBER() OVER (ORDER BY emp_id) AS rn,
     emp_id 
   FROM test1
 ) AS src
SET emp_id = src.rn
WHERE test1.emp_id = src.emp_id -- must be unique column(s)

Btw, instead of updating all rows of a table it might be better to INSERT/SELECT or MERGE the SELECT into a new table. You must do it if there's no unique column, you should if emp_id is the PI of your table (otherwise performance will be horrible).

Create table test1(
  emp_id decimal(5,0), 
  emp_name varchar(20),
  emp_no INTEGER GENERATED ALWAYS AS IDENTITY
         (START WITH 1
          INCREMENT BY 1
         )
);

Insert into test1(2015,'XYZ1',2);
Insert into test1(2016,'XYZ2',2);      
Insert into test1(2015,'XYZ3',null);
Insert into test1(2016,'XYZ4',null);      

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM