SQL Apprentice Question
hi, i've got a problem. i need to change order of records in my table . here
is the table
id forumname
----------------
1 test1
2 test2
3 test3
4 test4
i need to write code that can move nay record up or down without changing
id of forumname. i thought about another column called order
id forumname order
---------------------
1 test1 1
2 test2 2
3 test3 3
4 test4 4
but couldnt figureout how to change that order column. any one got an idea?
Celko Answers
Here is an old "cut & paste" for this problem: Given a motorpool with
numbered parking spaces, you want to move the automobiles around.
CREATE TABLE Motorpool
(parking_space INTEGER NOT NULL PRIMARY KEY
CHECK (parking_space > 0),
vin CHAR(17) NOT NULL);
Re-arrange the display order based on the parking_space column:
CREATE PROCEDURE SwapVehicles (@old_parking_space INTEGER,
@new_parking_space INTEGER)
AS
UPDATE Motorpool
SET parking_space
= CASE parking_space
WHEN @old_parking_space
THEN @new_parking_space
ELSE parking_space + SIGN(@old_parking_space - @new_pos)
END
WHERE parking_space BETWEEN @old_parking_space AND
@new_parking_space
OR parking_space BETWEEN @new_parking_space AND
@old_parking_space;
When you want to drop a few rows, remember to close the gaps with
this:
CREATE PROCEDURE CloseMotorpoolGaps()
AS
UPDATE Motorpool
SET parking_space
= (SELECT COUNT (M1.parking_space)
FROM Motorpool AS M1
WHERE M1.parking_space <= Motorpool.parking_space);
Original Source
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment