I have int datatype column as No, and want to find those No number which are missing in table.
For example: 1,2,3,7,8,9
Ans = 4,5,6
Thanks in advance.
I have int datatype column as No, and want to find those No number which are missing in table.
For example: 1,2,3,7,8,9
Ans = 4,5,6
Thanks in advance.
Try Following -
DECLARE @TABLE TABLE (NUM INT)
INSERT INTO @TABLE
VALUES
(1)
,(2)
,(3)
,(7)
,(8)
,(9)
DECLARE @MIN INT
DECLARE @MAX INT
SELECT @MIN = MIN(NUM) + 1, @MAX = MAX(NUM) - 1 FROM @TABLE
CREATE TABLE #TMP (FIELD_NO INT)
WHILE @MIN <= @MAX
BEGIN
IF NOT EXISTS (SELECT * FROM @TABLE WHERE NUM = @MIN)
INSERT INTO #TMP (FIELD_NO) VALUES (@MIN)
SET @MIN = @MIN + 1
END
SELECT * FROM #TMP
DROP TABLE #TMP
You can use a table of numbers
Here I use master..spt_values
that has the range 0-2047
. You can replace that with a numbers table of your own that has enough values.
declare @T table
(
Number int
);
insert into @T values (1),(2),(3),(7),(8),(9);
with MinMax as
(
select min(Number) as MinNumber,
max(Number) as MaxNumber
from @T
),
Number as
(
select N.Number
from master..spt_values as N
inner join MinMax as MM
on N.number between MM.MinNumber and MM.MaxNumber
where N.type = 'P'
)
select Number
from Number as N
where not exists
(
select *
from @T as T
where T.Number = N.number
)
order by N.number