SYBASE:SQL调用以查找第一个可用(岛)ID

时间:2015-02-11 02:53:42

标签: sql sybase

我需要返回一个特定长度的可用customerID的有序列表。

例如:

我需要在1500到3000之间找到FIRST 5未使用的customerID

Table= customer
Column= customerIDs
customerIDs value's= 1500,1502,1503,1507,1508
Return desired= 1501,1504,1505,1506,1509

我正在运行没有“TOP”命令的旧版SYBASE。到目前为止,我已经找到以下Query给我下一个可用的customerID(1501),但不知道如何修改它以返回前5个结果而不是1。

set rowcount 5 
SELECT  MIN(c.customerIDs )+1 AS NextID 
FROM customer c 
WHERE NOT EXISTS 
  (SELECT NULL 
    FROM customer cu 
    WHERE cu.customerIDs =c.customerIDs +1 
    AND cu.customerIDs >1500)
  AND c.customerIDs <3000

3 个答案:

答案 0 :(得分:0)

假设您正在使用set rowcount 5,这将限制查询返回5个结果。

但是,您正在使用MIN,这肯定只会返回1条记录。我想你想用

set rowcount 5 
SELECT  c.customerIDs +1 AS NextID 
FROM customer c 
WHERE (c.customerIDs + 1 BETWEEN 1500 and 3000)
  AND c.customerIDs + 1 NOT IN (SELECT c2.customerIDs
                   FROM customer c2)
ORDER BY c.customerIDs 

答案 1 :(得分:0)

这是一个有效的例子,扩展了David Faber的评论:

-- Create a temp table with all possible IDs
declare @min int, @max int
select @min = 1500, @max = 3000

create table #all_ids (id int)
insert #all_ids select @min

-- Keep doubling the number of rows until the limit is reached
while (select max(id) from #all_ids) < @max
begin
    insert #all_ids
    select id + (select count(*) from #all_ids)
    from #all_ids
    where id + (select count(*) from #all_ids) <= @max
end

-- Now find the 5 missing IDs by joining to the customer table on customerIDs, and only returning rows
-- where there is no match, i.e. customerIDs is null
set rowcount 5
select tmp.id
from #all_ids tmp
left join customer c
    on tmp.id = c.customerIDs
where c.customerIDs is null
order by tmp.id
set rowcount 0

答案 2 :(得分:0)

执行此操作的一个技巧是从master..spt_values表中动态生成序列,该表通常在大多数服务器中可用。 该表包含一个自然序列,可以连接到自身以生成更大的序列。例如:

create table #customer (customerID int)
go
insert #customer (customerID) values (1500)
insert #customer (customerID) values (1502)
insert #customer (customerID) values (1503)
insert #customer (customerID) values (1507)
insert #customer (customerID) values (1508)
go
set rowcount 5
select customerID
from (
  -- Generate a sequence of 1500-3000
  select 1500 + p2.number * 1000 + p1.number as customerID
  from 
    master..spt_values p1
  , master..spt_values p2
  where 
      p1.type = 'P'
  and p2.type = 'P'
  and p1.number between 0 and 999
  and p2.number between 0 and 1
  and p2.number * 1000 + p1.number <= 1500) seq
where customerID not in (select customerID from #customer)
order by 1
set rowcount 0
go

返回:

 customerID    
 ------------- 
 1501          
 1504          
 1505          
 1506          
 1509