Say i have a table with an integer column Id. I need to find the missing numbers in a sequence with a maximum returned amount.
How can i achive this in one single query using MS SQL?
Thanks in advance!
Try this:
If you need to get more numbers, just increase the WHERE Number<=100.
DECLARE @Tab1 TABLE (ID INT)
INSERT INTO @Tab1 VALUES(1)
INSERT INTO @Tab1 VALUES(3)
INSERT INTO @Tab1 VALUES(5)
INSERT INTO @Tab1 VALUES(7)
INSERT INTO @Tab1 VALUES(9)
;WITH CTE AS
(
SELECT 1 AS Number
UNION ALL
SELECT Number + 1 FROM CTE
WHERE Number<=100
)
SELECT TOP 5 *
FROM CTE
WHERE Number NOT IN(SELECT ID FROM @Tab1)
ORDER BY Number
OPTION (maxrecursion 0);
Existing values:
Number
1
3
5
7
9
OutPut:
Number
2
4
6
8
10
Hope this helps you.
This should work
There are also a system table with numbers
declare @T table (i int primary key);
insert into @T values (1), (2), (4), (6), (9);
declare @count int = 10;
declare @size int = (select count(*) from @T);
with cte as
( select 1 as num
union all
select num + 1
from cte
where num + 1 <= (@count + @size)
)
select top (@count) cte.num
from cte
left join @T t
on t.i = cte.num
where t.i is null
order by cte.num
option ( MaxRecursion 0 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With