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
WITH tempTable AS
(
SELECT OrderRankInt, ROW_NUMBER() OVER (ORDER BY OrderRankInt) AS rn
FROM dbo.[Table]
WHERE sectionId = @sectionId
)
UPDATE tempTable
SET OrderRankInt = rn;
END
GO
source
share