如何从 sql 中的索引 [order] table 中找出缺失的记录 (ID)

How to fiind out the missing records (ID) from an indexed [order] table in sql

我有一个 table [Order],其中包含具有顺序 ID 的记录(仅奇数,即 1,3,5,7...989, 991, 993, 995, 997, 999 ), 看到有几条记录被不小心删除了,应该重新插入,首先要找出当前table里少了哪些记录,这个table里有几百条记录

不知道怎么写查询,有没有好心人帮忙?

我在考虑是否必须编写存储过程或函数,但如果出于环境原因可以避免它们会更好。

下面的伪代码是我的想法:

set @MaxValue = Max(numberfield)
set @TestValue = 1
open cursor on recordset ordered by numberfield
foreach numberfield
 while (numberfield != @testvalue) and (@testvalue < @MaxValue) then
  Insert @testvalue into #temp table
  set @testvalue = @textvalue + 2
 Next
Next

更新:

预期结果:

订单 ID = 7 应该作为唯一缺失的记录被拾取。

更新二:

如果我使用

WHERE
    o.id IS NULL;

它returns没什么:

我们可以尝试加入一个数字 table,其中包含您可能希望出现在您自己的 table 中的所有奇数。

DECLARE @start int = 1
DECLARE @end int = 1000

WITH cte AS (
    SELECT @start num  
    UNION ALL
    SELECT num + 2 FROM cte WHERE num < @end 
)

SELECT num
FROM cte t
LEFT JOIN [Order] o
    ON t.num = o.numberfield
WHERE
    o.numberfield IS NULL;

由于没有得到您的回复,我在评论中更改了脚本,以便您相应地填写:

declare @id int
declare @maxid int

set @id = 1
select @maxid = max([Your ID Column Name]) from [Your Table Name]

declare @IDseq table    (id int)

while @id < @maxid --whatever you max is
begin
    insert into @IDseq values(@id)

    set @id = @id + 1
end

select 
    s.id 
from        @IDseq s 
left join   [Your Table Name] t on s.id = t.[Your ID Column Name]
where t.[Your ID Column Name] is null

在您看到 [Your ID Column Name] 的地方,将所有内容替换为您的列名,[Your Table Name].

也是如此

我相信这会给你想要的结果。