如何获取第一个不连续的数字?

BestAns1 2002-08-05 02:34:14
sql server 中一个字段 Num,全是数字,没有重复。我如何能找出第一个不连续的数字?比如共 6 条记录,Num 分别是:1,2,3,5,6,那么第一个就是 4。
各位有办法吗?
...全文
192 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Yang_ 2002-08-05
  • 打赏
  • 举报
回复
捣乱有理!

虽然按钮给了很好的方法,但我的有错误,会死循环,更正一下:

declare @Num int
select @Num=max(num) from tablename

declare @i int
declare @Temp table (Num int)

set @i=1

while @i<=@Num+1 --- 如果全部连续,得到@Num+1
begin
insert @Temp values(@i)
set @i=@i+1
end
select @Num=(
select top 1 num from @Temp a
where not exists (
select * from tablename where num=a.num
)
order by num
)

newly_ignorant 2002-08-05
  • 打赏
  • 举报
回复
我是来捣乱的,赫赫。

什么叫第一个不连续数字,指最小的不连续数字吧。

比如2,3,4,6 应该是5还是1?
Yang_ 2002-08-05
  • 打赏
  • 举报
回复
updated:

declare @Num int
select @Num=max(num) from tablename

declare @i int
declare @Temp table (Num int)

set @i=1

while @i<=@Num+1 --- 如果全部连续,得到@Num+1
insert @Temp values(@i)

select @Num=(
select top 1 num from @Temp a
where not exists (
select * from tablename where num=a.num
)
order by num
)
Yang_ 2002-08-05
  • 打赏
  • 举报
回复
declare @Num int
select @Num=max(num) from tablename

declare @i int
declare @Temp table (Num int)

set @i=1

while @i<=@Num+1 --- 如果全部连续,得到@Num+1
insert @Temp values(@i)

select @Num=(
select top 1 num from @Temp a
where not exists (
select * from tablename where num=a.num
)
)


yonghengdizhen 2002-08-05
  • 打赏
  • 举报
回复
楼上的方法不错..
yonghengdizhen 2002-08-05
  • 打赏
  • 举报
回复
用存储过程,游标逐行测试.
用一个查询也可以完成,不过太麻烦.思路是使用自连接.
连接条件是该字段和该字段加一的值,在连接限制上采用left join
icevi 2002-08-05
  • 打赏
  • 举报
回复
select top 1 num+1
from yourtable t1
where not exists
(select num from yourtable t2 where t2.num=t1.num+1)
order by num

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧