SQL 服务器 - 在数字包含前面的零的序列中查找缺失的数字

SQL Server - Find Missing Numbers in sequence where numbers contain preceding zeros

我将数字按顺序存储在数据库中,这些数字存储为文本并包含前面的零。

Numbers
-------
001
002
003
004
006
007
010
011
-------

查询应该找到以下结果

Missing
-------
005
008
009
-------

谢谢。

你只需要一个数字序列table(SO中已经有很多实现)然后使用LEFT JOIN。请参阅以下查询:seq 是从 1 到 9999 的数字序列,如 int.

;with seq as 
(
select top 9999 row_number() over(order by t1.number) as N
from   master..spt_values t1 
       cross join master..spt_values t2

)

SELECT RIGHT('000'+CAST(s.n AS VARCHAR(3)),3) as MissingNumbers
from seq s 
left join yourtable t on s.n = cast(t.Number as int)
where t.number is null