I have a column “SortIndex” in a table, and I would like to add a “case update” to reorder that table by passing in ID and the new position of the chosen one.
DECLARE @T TABLE
(
ID int,
Name char(1),
SortIndex int
)
INSERT @T
SELECT 21, 'A', 1 UNION ALL
SELECT 23, 'B', 2 UNION ALL
SELECT 35, 'C', 3 UNION ALL
SELECT 45, 'D', 4 UNION ALL
SELECT 55, 'E', 5
SELECT * FROM @T
DECLARE @SortIndex int
/* MOVE A -> 4 */
SET @SortIndex = (SELECT SortIndex FROM @T WHERE ID = 23)
/*
UPDATE @T
SET
SortIndex = CASE ... ??
*/
/* MOVE D -> 2 */
SELECT * FROM @T
Is this possible to solve this by only using the case statement to rebuild the sortindex’es?
UPDATE
Desired results
A -> 4
Name SortIndex
B 1
C 2
D 3
A 4
E 5
D -> 2
A 1
D 2
B 3
C 4
E 5
Use following code to move and rebuild indexes, it adds element after desired elements and shifts others (answer based on the comment clarifications ) :
This is slimmer version:
Full example of moving A to position 2, also sqlfidle link http://sqlfiddle.com/#!3/d41d8/5918:
Initial version: