Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
tonyr1971
Starting Member
5 Posts |
Posted - 2009-04-29 : 06:31:29
|
| Hi All,If I have a table with the following data, I want to change the sequence of any item, is there an elegant SQL way of doing this?For example:My table is:ObjectID nvarchar(8)Sequence intData is:Fridge1 1Fridge2 2Fridge3 4Fridge4 3Fridge5 5If I want to move Fridge5 to the top, as in:Fridge1 2Fridge2 3Fridge3 5Fridge4 4Fridge5 1I have to update all the other Sequence in the table for the correct order. I know I could setup a temp table and re-order the sequence.Is there a better way?CheersTony |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2009-04-29 : 06:47:26
|
BEGIN TRANUPDATE Table1SET Sequence = 0WHERE ObjectID = 'Fridge5'UPDATE fSET Sequence = recIDFROM (SELECT Sequence, ROW_NUMBER() OVER (ORDER BY Sequence) AS recIDFROM Table1) AS fCOMMIT TRAN E 12°55'05.63"N 56°04'39.26" |
 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2009-04-29 : 06:57:09
|
[code]UPDATE fSET Sequence = recIDFROM ( SELECT Sequence, ROW_NUMBER() OVER (ORDER BY CASE WHEN ObjectID = 'Fridge5' THEN 0 ELSE 1 END, Sequence) AS recID FROM Table1 ) AS f[/code] E 12°55'05.63"N 56°04'39.26" |
 |
|
|
tonyr1971
Starting Member
5 Posts |
Posted - 2009-04-29 : 07:02:48
|
| Wow, superb! |
 |
|
|
|
|
|