如何从序号中找出缺失的数字?

时间:2014-02-16 12:35:13

标签: oracle

我得到的table1包含1到100之间的序列号 我想在没有创建新表的情况下使用pl输出缺失的数字

我试图通过这种方式去做,但绝对不是专业的方式 我试着用 选择min_val.nextval关键字,但我失败了所以任何简单而专业的方式来做到这一点

declare 
min_val number(4);
max_val number(4);
current_val number(4);


cursor ids_cur is 
select ids from test1;

begin 

for ids_rec in ids_cur
loop
if min_val is not null then 
min_val:=min_val+1;
DBMS_OUTPUT.PUT_LINE(min_val);
else
DBMS_OUTPUT.PUT_LINE(min_val);

end if;
end loop;
end;

2 个答案:

答案 0 :(得分:2)

执行此类查询的最有效方法是使用select语句而不是游标。基于集合的操作更快。这是一种使用递归CTE的方法:

with nums(n) as (
      select 1 as n from dual
      union all
      select n + 1
      from nums
      where n < 100
     )
select nums.n as MissingId
from nums left outer join
     test1
     on nums.n = test1.id
where test1.id is null;

这应该很容易推广到9,999个值。

如果您只是想知道数字是否缺失,还有其他方法。

答案 1 :(得分:0)

我想出了这个解决方案,但是我收到的错误信息是fetch返回多行但是我正在从记录中读取光标是什么??!

declare 
current_num number(4);

cursor c1 is 
select ids from test1;

 BEGIN

 for rec in c1 
 loop
select rownum into current_num from  all_objects  
   where  rownum<=(select max(ids) from  test1)  
   minus
   select ids
   from test1;

   DBMS_OUTPUT.PUT_LINE(current_num);
 end loop;
 END;