Domanda

Suppose I have a table called Class with the following columns...

ClassID INT
ClassName VARCHAR(100)
SortOrder INT

Suppose this table has 10 rows (10 classes) in it. Now suppose I know my current class ID, and I need to "go forward" X number of classes (based on their sort order) and get the record/row for the new class. I need this to handle "looping around", meaning if the current class sort order is 7 and X=5, the new class id would be 2 (it would loop around to 1 when it gets to 10 and continue counting).

I have this so far:

DECLARE @OffsetClasses INT = 5 -- This gets populated (not hard coded, but that is not relevant to the issue)

DECLARE @NewClassID INT = (SELECT TOP 1 ClassID
                           FROM Classes
                           ORDER BY SortOrder
                           OFFSET @OffsetClasses ROWS);

... But this does not loop around, the OFFSET syntax does not seem to work together with ORDER BY, and OFFSET does not seem to support a variable for the number of rows.

What is the easiest and fastest way to do this in SQL Server 2008? Do I have to use a cursor (I prefer not to)?

È stato utile?

Soluzione

You can do this using modulo operator. These three values you know:

DECLARE @OffsetClasses INT = 5
DECLARE @CurrentID INT = 7
DECLARE @ClassesCount INT = 10

Then it's trivial to get the current sort order:

DECLARE @CurrentSortOrder INT
select @CurrentSortOrder = SortOrder from Classes where ClassID = @CurrentID

Assuming your sort order is a raising sequence from 1 to 10 with no gaps then next row can be retrieved like this:

select * from Classes 
where SortOrder = (@CurrentSortOrder + @OffsetClasses - 1) % @ClassesCount + 1
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top