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.

 All Forums
 General SQL Server Forums
 Database Design and Application Architecture
 Ordering records - efficiently

Author  Topic 

stewsterl
Starting Member

2 Posts

Posted - 2008-02-08 : 13:47:11
I hope I explain this correctly...

I'm required to allow users to order items in a field to be displayed on a page in the order they specified.

For example: A user can drag and drop items in a list to specify the order it will be displayed in.

I have my drag and drop code ready to do this.
I have an idea on how to do this but I think it’s too inefficient.
I was going to create an orderby field and populate it with a number that corresponds to the position of the item. However, as one can deduce, if a user drags and drops a record between two others, I would have to change not only its orderby number but then change all the other items orderby number.

For instances if I dropped an item with an orderby number of 3 between 6 and 7 I would have to change the 3 to a 7 and then recursively change all the other records orderby numbers up to 3 and then change everything after 7.

Well, I hope I make sense. It’s easier to visualize it on paper.

Does anyone know how to tackle this issue of user dynamic ordering?

jdaman
Constraint Violating Yak Guru

354 Posts

Posted - 2008-02-08 : 14:48:52
You could do something like this:
DECLARE @a TABLE ( OrderId INT, Col CHAR(1) )
INSERT @a ( OrderId, Col )
SELECT 1, 'A' UNION
SELECT 2, 'B' UNION
SELECT 3, 'C' UNION
SELECT 4, 'D' UNION
SELECT 5, 'E' UNION
SELECT 6, 'F'

DECLARE @Order INT, @Col CHAR(1)

SELECT @Order = 4, @Col = 'A'

UPDATE @a
SET OrderId = rn
FROM @a a
JOIN ( SELECT ROW_NUMBER() OVER ( ORDER BY OrderId, NewInd ) AS rn,
Col
FROM ( SELECT OrderId,
NULL AS NewInd,
Col
FROM @a
WHERE Col <> @Col
UNION
SELECT @Order,
1,
@Col
) a
) b ON a.Col = b.Col

SELECT * FROM @a
ORDER BY OrderId
Go to Top of Page

JasonL
Starting Member

35 Posts

Posted - 2008-02-08 : 18:38:40
May be you could changed the orderby value to like
300
400
500
600
700
and the update become changing 300 to 650 or something like that

JasonL (from Microsoft)
http://blogs.msdn.com/usisvde/
Go to Top of Page
   

- Advertisement -