作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
假设我有一个 sql server 表:
公司名称
2佛瑞德3佛瑞德4佛瑞德6佛瑞德7佛瑞德8佛瑞德11佛瑞德
我需要一种有效的方法来传入参数 [StartingNumber] 并按顺序从 [StartingNumber] 开始计数,直到找到丢失的数字。
例如,请注意表中缺少 1、5、9 和 10。
如果我提供参数 [StartingNumber] = 1,它会检查 1 是否存在,如果存在,它会检查 2 是否存在,依此类推,因此 1 将在此处返回。
如果 [StartNumber] = 6,该函数将返回 9。
在 c# 伪代码中,它基本上是:
int ctr = [StartingNumber]
while([SELECT NumberTaken FROM tblNumbers Where NumberTaken = ctr] != null)
ctr++;
return ctr;
最佳答案
我称我的表为空白,并使用了以下内容:
declare @StartOffset int = 2
; With Missing as (
select @StartOffset as N where not exists(select * from Blank where ID = @StartOffset)
), Sequence as (
select @StartOffset as N from Blank where ID = @StartOffset
union all
select b.ID from Blank b inner join Sequence s on b.ID = s.N + 1
)
select COALESCE((select N from Missing),(select MAX(N)+1 from Sequence))
declare @StartOffset int = 2
; With BlankFilters as (
select ID from Blank where hasEntered <> 1
), Missing as (
select @StartOffset as N where not exists(select * from BlankFilters where ID = @StartOffset)
), Sequence as (
select @StartOffset as N from BlankFilters where ID = @StartOffset
union all
select b.ID from BlankFilters b inner join Sequence s on b.ID = s.N + 1
)
select COALESCE((select N from Missing),(select MAX(N)+1 from Sequence))
create table Blank (
ID int not null,
Name varchar(20) not null
)
insert into Blank(ID,Name)
select 2 ,'Fred' union all
select 3 ,'Fred' union all
select 4 ,'Fred' union all
select 6 ,'Fred' union all
select 7 ,'Fred' union all
select 8 ,'Fred' union all
select 11 ,'Fred'
go
关于sql - 如何在从参数开始并按顺序递增的表字段中找到缺失的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4025341/
我是一名优秀的程序员,十分优秀!