使用SQL从范围中选择最低未使用的数字

时间:2012-09-19 19:23:54

标签: sql-server-2008 stored-procedures

我的表有一个'location'字段,范围从1到25.我使用以下SQL来返回当前未使用的最低'位置';

select top 1 field from [dbo].[misc_fields] where field NOT IN (select location from ListFields where listid = @listid) order by field

这个问题在于它依赖于misc_fields表,该表包含每个位置的行(1-25)。我想删除需要这个查找表,只需在存储过程本身中定义范围。

3 个答案:

答案 0 :(得分:2)

这是我现在能想到的最好的,虽然比你的要复杂得多;

SELECT MIN(pos) AS nextlocation FROM
(
  SELECT location, ROW_NUMBER() OVER (ORDER BY location) AS pos
  FROM ListFields WHERE listid=1
  UNION
  SELECT 0, MAX(location)+1
  FROM ListFields WHERE listid=1
) a
WHERE location<>pos;

请注意,这不仅限于25,它可能会给出26,所以你需要自己在别处检测你的限制。

SQLfiddle here to try it out

答案 1 :(得分:0)

此解决方案无效。哔叽。

尝试使用IDENTITY function

SELECT MIN(artificial_table.id) FROM your_table RIGHT JOIN 
(SELECT TOP 25 IDENTITY(int,1,1) AS id) AS artificial_table 
ON your_table.id = artificial_table.id WHERE your_table.id IS NULL

答案 2 :(得分:-1)

取自Martin Smith提供的链接;

 WITH Locations (Location) AS 
        ( 
         SELECT 1 UNION ALL 
         SELECT 1 + Location FROM Locations WHERE Location < 26 
        ) 

SELECT Location INTO #Locations FROM Locations 

SELECT TOP 1 Location from #Locations where Location NOT IN (select location from ListFields where listid = @listid) order by Location

DROP TABLE #Locations