Update SQL with consecutive numbering

前端 未结 10 613
庸人自扰
庸人自扰 2020-12-02 20:16

I want to update a table with consecutive numbering starting with 1. The update has a where clause so only results that meet the clause will be renumbered. Can I accomplish

10条回答
  •  日久生厌
    2020-12-02 20:34

    As well as using a CTE or a WITH, it is also possible to use an update with a self-join to the same table:

    UPDATE a
    SET a.columnToBeSet = b.sequence
    FROM tableXxx a
    INNER JOIN
    (
       SELECT ROW_NUMBER() OVER ( ORDER BY columnX ) AS sequence, columnY, columnZ
       FROM tableXxx
       WHERE columnY = @groupId AND columnY = @lang2
    ) b ON b.columnY = a.columnY AND b.columnZ = a.columnZ
    

    The derived table, alias b, is used to generated the sequence via the ROW_NUMBER() function together with some other columns which form a virtual primary key. Typically, each row will require a unique sequence value.

    The WHERE clause is optional and limits the update to those rows that satisfy the specified conditions.

    The derived table is then joined to the same table, alias a, joining on the virtual primary key columns with the column to be updated set to the generated sequence.

提交回复
热议问题