Reset or update an integer row row in a database table

I am working on a stored procedure in SQL Server 2008 to flush an integer column in a database table. This integer column stores or preserves the display order of line items. Users can drag and drop items in a specific sort order, and we save this order in the database table using this “Order Ranking Center”.

Display queries for items always add "ORDER BY OrderRankInt" when retrieving data, so the user sees the items in the order indicated earlier.

The problem is that this integer column collects many duplicate values ​​after the table items are reordered. Hence,...

Table
--------
Name | OrderRankInt
a    | 1
b    | 2
c    | 3
d    | 4
e    | 5
f    | 6

After much reordering, the user becomes ....

Table
--------
Name | OrderRankInt
a    | 1
b    | 2
c    | 2
d    | 2
e    | 2
f    | 6

These duplicates are mainly due to insertions and user-defined order numbers. We are not trying to prevent the duplication of rows of orders, but we need a way to "Fix" the table on the inserts of elements / changes.

Is there a way so that I can reset the OrderRankInt column with one UPDATE query? Or do I need to use a cursor? What does the syntax for this cursor look like?

Thanks, Kervin

EDIT

Update using Remus Rusanu . Thanks!!

CREATE PROCEDURE EPC_FixTableOrder
@sectionId int = 0
AS
BEGIN

-- "Common Table Expression" to append a 'Row Number' to the table
WITH tempTable AS 
(
    SELECT OrderRankInt, ROW_NUMBER() OVER (ORDER BY OrderRankInt) AS rn
    FROM dbo.[Table]
    WHERE sectionId = @sectionId -- Fix for a specified section
)
UPDATE tempTable        
SET OrderRankInt = rn;  -- Set the Order number to the row number via CTE

END
GO
+3
source share
2 answers
with cte as (
 select OrderId, row_number() over (order by Name) as rn
 from Table)
update cte
 set OrderId = rn;

This does not take into account any relationship with foreign keys, I hope you took care of this.

+5

. , NULL, , .

( .)

+2

Source: https://habr.com/ru/post/1722719/


All Articles