How to Update a Column Base on a Row Number in Mssql

Just recently I was asked to normalized or divide a table into 2 tables. Unfortunately, the only column that linked them (email) allows multiple same values, even aggregate would not do (email, password, etc). This is because there's a field that marks a user as inactive. So a single email can have many inactive records.

So linking the 2 tables, I only have 1 choice to update the other table based on row number, since the first table is filled with auto number.

How did I update a column base on a row number? See:

UPDATE Users
SET MainTableId=t.Seq
FROM (SELECT id, Row_Number() OVER (ORDER BY id) as Seq FROM Users) t
INNER JOIN Users ON t.id=Users.id

--test the table if properly updated
select * from Users

1 Comments

Post a Comment

Post a Comment

Previous Post Next Post
NERV Open Source
Building production Spring Boot systems?

Explore NERV — open-source Java libraries for audit trails, persistence, exception handling, and reliable event-driven architecture.