I need an efficient way to pass in a parameter [StartingNumber] and to count from [StartingNumber] sequentially until I find a number that is missing.
I use the following sql to get the next number:
DECLARE @StartOffset int
SET @StartOffset = 23
; With Missing as (
select @StartOffset as N where not exists(
select * from [QUEUE] where QueueNum = @StartOffset AND ismelutash = 1)
), Sequence as
( select @StartOffset as N from [QUEUE] where QueueNum = @StartOffset
union all
select b.QueueNum from [QUEUE] b inner join Sequence s
on b.QueueNum = s.N + 1 and b.ismelutash = 1
)
select COALESCE((select N from Missing),(select MAX(N)+1 from Sequence))
It has been working for awhile but now when I run it I get 'The statement terminated. The maximum recursion 100 has been exhausted before statement completion.'
Anyone have any ideas? Thanks
EDIT:
I added maxrecursion but it just loads and doesn't return data:
DECLARE @StartOffset int
SET @StartOffset = 50
DECLARE @isMelutash int
SET @isMelutash = 0
; With QueueFilters as (
select queuenum from queue where ismelutash = 1
), Missing as (
select @StartOffset as N where not exists(select * from QueueFilters where queuenum = @StartOffset)
), Sequence as (
select @StartOffset as N from QueueFilters where queuenum = @StartOffset
union all
select b.queuenum from QueueFilters b inner join Sequence s on b.queuenum = s.N + 1
)
select COALESCE((select N from Missing ),(select MAX(N)+1 from Sequence ) )
**OPTION(MAXRECURSION 150)**