There is one table T ( id integer, primary key ( id).
I want a parameterized query that, given id i:
will return next consecutive id,
if i = biggest id in T, query should return the smallest id in T (cyclical)
views:
83answers:
2
+1
A:
This appears to be what you're looking for:
CREATE PROCEDURE dbo.ProcName
(
@ID INTEGER
)
AS
SELECT TOP 1 id
FROM table
WHERE id > @ID
ORDER BY id
Dave
2010-04-21 19:59:53
the OP wants it to return the smallest ID again when the greatest ID has been reached (cyclic)...
AdaTheDev
2010-04-21 20:02:46
How is this meeting the OP's cyclical behavior when id>= max?
Jim Leonardo
2010-04-21 20:03:28
+3
A:
You can select the smallest id over the value @i (if any), and the smallest id, then get the largest:
select max(id)
from (
select top 1 id
from T
where id > @i
order by id
union all
select top 1 id
from T
order by id
) x
Or perhaps:
select max(id)
from (
select min(id) as id
from T
where id > @i
union all
select min(id)
from T
) x
Guffa
2010-04-21 20:00:53
thanks, exactly what I was looking for, now I need to check if max/min works on strings.. it does.
Marcin K
2010-04-21 20:14:19
@Marcin: Max and min works on strings, but it does a textual comparison. If you have numerical vales stored as strings, you have to convert them to numbers in the query, as for example '2' > '10'.
Guffa
2010-04-22 04:48:37