SQL Bubble Sort

Status
Not open for further replies.

Slingblade

Smack-Fu Master, in training
85
Anyone have a script that updates the sort order of a table. Like if item 2 became 1 in the sort order the script would change the other records sort numbers. Previous 1 would become 2, 3 unchanged etc. Also, if 3 became 1 then 1 would become 2 and 2 would become 3.


id | sort | otherinfo
----------------------
32 | 1 |Bob
67 | 2 |James
88 | 3 |William


Pointers to articles about this welcome.

Thanks!
 

TheJet

Ars Praefectus
4,598
Subscriptor++
Hrm...

UPDATE TABLE SET sortorder = -1 where id = [id to place]
UPDATE TABLE SET sortorder = sortorder + 1 WHERE sortorder >= [place you are putting id] AND sortorder < [place where id was]
UPDATE TABLE SET sortorder = [place where id is going] WHERE id = [id to place]

You could probably do it with just two statements if you don't care the actual values, just that one is relatively higher/lower than the others, but this will keep your sort as close to what it originally was as possible.

TheJet
 
Status
Not open for further replies.