Update SQL with consecutive numbering

前端 未结 10 591
庸人自扰
庸人自扰 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:46

    I've used this technique for years to populate ordinals and sequentially numbered columns. However I recently discovered an issue with it when running on SQL Server 2012. It would appear that internally the query engine is applying the update using multiple threads and the predicate portion of the UPDATE is not being handled in a thread-safe manner. To make it work again I had to reconfigure SQL Server's max degree of parallelism down to 1 core.

    EXEC sp_configure 'show advanced options', 1;
    GO
    RECONFIGURE WITH OVERRIDE;
    GO
    EXEC sp_configure 'max degree of parallelism', 1;
    GO
    RECONFIGURE WITH OVERRIDE;
    GO
    
    DECLARE  @id int
    SET @id = -1
    UPDATE dbo.mytable
    SET @id = Ordinal = @id + 1
    

    Without this you'll find that most sequential numbers are duplicated throughout the table.

提交回复
热议问题