I have a table like this:
SELECT ID, Rank
FROM FAQ
ORDER BY Rank ASC;
ID | Rank |
---|---|
21 | 1 |
25 | 2 |
30 | 3 |
23 | 4 |
24 | 5 |
26 | 6 |
27 | 7 |
28 | 8 |
29 | 9 |
22 | 10 |
Now, I'm updating a row:
UPDATE FAQ SET
Rank = 8
WHERE ID = 30;
SELECT ID, Rank
FROM FAQ
ORDER BY Rank ASC;
ID | Rank |
---|---|
21 | 1 |
25 | 2 |
23 | 4 |
24 | 5 |
26 | 6 |
27 | 7 |
28 | 8 |
30 | 8 |
29 | 9 |
22 | 10 |
My question: is there a way to update the other row ID (23, 24, 26, 27, 28) from original Rank (4, 5, 6, 7, 8) to new Rank (3, 4, 5, 6, 7), respectively?
I have tried:
DECLARE @SrNo SMALLINT = 0;
UPDATE FAQ SET @SrNo = Rank = @SrNo + 1;
after the update but to no avail, as it will just return the Rank value as per the first image.
Thanks in advance.
3条答案
按热度按时间z2acfund1#
You can use the code below and create a stored procedure:
We are using
ROW_NUMBER
in order to order the data based on the new rank value for a particular row. For rows with the same value, the updated one is treated as bigger.zzlelutf2#
A slightly different, and possibly more efficient, version of @gotqn's excellent answer:
Essentially, you begin by looking up the existing rank of the single row you want to move.
Then take all the rows between that rank and the new rank (taking the lower and higher of those in order). Update that set of rows as follows: if it's the row we want to change, set it to
@Rank
, otherwise add to it theSIGN
of the difference between the rank moves ie +1 or -1. This therefore works no matter which direction the row is moving.It also does not require a sort on the rows, as long as there is an index on
ID
db<>fiddle
06odsfpq3#
Generate
Row_Number
order byId
and hopefully it will satisfy your desired output. Make sure how you generating Rank order by. Because 22 with rank 10Generation of the Rank on the fly is best approach instead of storing in the table.