I have a table with data like.
ItemCode
1000
1002
1003
1020
1060
I am trying to write an SQL statement to get the minimum number (ItemCode) that is NOT in this table, and it should be able to get the next lowest number after the previous minimum order ID has been inserted into the table, but also skip the numbers that are already in the database. I want to get only one result each time the query is executed.
Thus, it should get 1001as the first result based on the table above. After it has ItemCode = 1001been inserted into the table, the next result that it should get should be 1004, because 1000before 1003already exists in the table.
Based on everything I've seen on the Internet, I think I need to use the While loop for this. Here is my code I'm still working on.
DECLARE @Count int
SET @Count= 0
WHILE Exists (Select ItemCode
from OITM
where itemCode like '10%'
AND convert(int,ItemCode) >= '1000'
and convert(int,ItemCode) <= '1060')
Begin
SET @COUNT = @COUNT + 1
select MIN(ItemCode) + @Count
from OITM
where itemCode like '10%'
AND convert(int,ItemCode) >= '1000'
and convert(int,ItemCode) <= '1060'
END
I feel that there should be an easier way to achieve this. Is there any way to tell me ...
select the minimum number from 1000 to 1060 that does not exist in table X
EDIT: creating a new table in my case is not an option
Final Edit: Thanks guys! I understood. Here is my last query that returns exactly what I want. I knew I was doing it too hard for no reason!
With T0 as ( select convert(int,ItemCode) + row_number() over (order by convert(int,ItemCode)) as ItemCode
from OITM
where itemCode like '10%'
AND convert(int,ItemCode) >= '1000'
And convert(int,ItemCode) <= '1060')
Select MIN(convert(varchar,ItemCode)) as ItemCode
from T0
where convert(int,ItemCode) Not in (Select convert(int,ItemCode)
from OITM
where itemCode like '10%'
AND convert(int,ItemCode) >= '1000'
and convert(int,ItemCode) <= '1060');