简体   繁体   中英

How to sort the row of record and update dynamically in SQL?

Clarification on SQL query syntax : we have an Employee table which has two columns Emp Id and EmpName and its values looks like this:

100, a
200, b
300, c

I have to update the EmpName for 100 with "Joe", 200 with "John", 300 with "Sam". These same 3 names then need to repeat in order for the rest of the table.

How to pick EmpId in ascending order sequence and update the EmpName accordingly?

WITH cteRowNums AS (
    SELECT EmpId,
           EmpName,
           ROW_NUMBER() OVER(ORDER BY EmpId) AS RowNum
        FROM Employee
)
UPDATE cteRowNums
    SET EmpName = CASE WHEN RowNum % 3 = 1 THEN 'Joe'
                       WHEN RowNum % 3 = 2 THEN 'John'
                       WHEN RowNum % 3 = 0 THEN 'Sam'
                  END;

Hi please add a row_num column after that update using ROW_NUMBER() something like

 Alter table emp1 add row_num varchar(10)

    with cte as (
 select id,name,row_num,ROW_NUMBER() over (order by [id]) as rn
 from emp1
 )
 update cte set row_num = 'Test'+ convert(varchar,rn)

row_number this will create a ordered column regarding [Emp Id]. and run update statement to get desired result.

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