Vivek Harry
Vivek Harry

Reputation: 439

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?

Upvotes: 1

Views: 8195

Answers (2)

access_granted
access_granted

Reputation: 1907

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);      

Upvotes: 1

dnoeth
dnoeth

Reputation: 60462

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).

Upvotes: 2

Related Questions