-3

我有一个表,其“位置”字段的范围从 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) 的一行。我想消除拥有此查找表的需要,而只需在存储过程本身中定义范围。

4

3 回答 3

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 在这里尝试一下

于 2012-09-19T19:51:51.533 回答
0

此解决方案不起作用。哔叽。

尝试使用IDENTITY 功能

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
于 2012-09-19T20:00:28.213 回答
-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
于 2012-09-19T21:05:27.967 回答