我有一个名为Student
的表和名为StudentNumber
学生表
StudentNumber
-------------
1
2
3
4
5
8
10
期待输出
6
7
9
我试过以下
Declare @trans int;
set @trans = 1;
while(@trans <=50000)
BEGIN
if((select StudentNumber from [Student] where StudentNumber = @trans) != @trans)
BEGIN
print @trans;
END
END
set @trans = @trans + 1;
答案 0 :(得分:0)
试试这个;
declare @id int
declare @maxStudentNumber int
set @id = 1
select @maxStudentNumber = max(StudentNumber) from Student
create table #MissingIds
(
id int
)
while @id < @maxStudentNumber
begin
insert into #MissingIds values(@id)
set @id = @id + 1
end
select m.id
from #MissingIds m
left join Student s
on m.id = s.StudentNumber
where s.StudentNumber is null
drop table #MissingIds
答案 1 :(得分:0)
您可以使用(SQL Server 2016及更高版本):
SELECT Number
FROM (select cast([key] as int) +
(SELECT MIN(StudentNumber) FROM Students) as number
from OPENJSON( '[1'
+ replicate(',1',(SELECT MAX(StudentNumber) FROM Students)-
(SELECT MIN(StudentNumber) FROM Students))+']')) n
LEFT JOIN Students s
ON n.number = s.StudentNumber
WHERE s.StudentNumber IS NULL;
<强> DBFiddle Demo 强>
注意:您可以将第一个子查询与任何其他计数数字生成器交换。 更多信息:SQL, Auxiliary table of numbers
答案 2 :(得分:0)
应该如下所示
Declare @trans int;
set @trans = 1;
while(@trans <=50000)
BEGIN
if NOT EXISTS (select StudentNumber from [Student] where StudentNumber = @trans)
BEGIN
print @trans;
END
END
set @trans = @trans + 1;
答案 3 :(得分:0)
您可以执行以下操作
;with report as(
select 1 as missing
union all
select missing + 1
from report
where missing < @max
)
select *
from report m
where not exists ( select 1 from student s where s.id = m.missing)
option (maxrecursion 0);
这是一个有效的demo
结果
missing
6
7
9
希望这会对你有所帮助
答案 4 :(得分:0)
你可以试试这个:
select m.number from
(select min(StudentNumber) a,max(StudentNumber) b from Students) c ,master..spt_values M
where c.a <= m.number
and c.b > = m.number
and type ='P'
and m.number not in (select StudentNumber from Students)