查询获取丢失的序列号列表

时间:2014-06-26 17:21:33

标签: sql-server

我设置了一个查询订单表的查询,并获取了缺失的连续订单号列表,因此我们可以使用该列表来帮助跟踪缺失的订单。
它似乎工作得很好,只是如果连续多于一个,我只得到第一个数字 所以,如果结果应该是:1,5,6,10 我改为:1,5,10 省略了6

我不是SQL大师,我无法弄清楚代码中要改变什么,以确保我得到所有这些。这是我的代码:

DECLARE @maxorder INT
SET @maxorder = (SELECT MAX(CAST(TranNo) AS INT)
FROM SalesOrder 
WHERE TranDate 
BETWEEN getdate()-1 AND DATEADD(DAY, 1, GETDATE()))
SELECT a.offset AS Missing
FROM 
(SELECT 1 AS Offset
UNION
SELECT CAST((TranNo) AS INT) + 1
FROM SalesOrder
WHERE TranDate BETWEEN GETDATE()-1 AND DATEADD(DAY, 1, GETDATE())) a
LEFT JOIN
(SELECT CAST((TranNo) AS INT) AS TranNum 
FROM SalesOrder 
WHERE TranDate BETWEEN getdate()-1 AND DATEADD(DAY, 1, GETDATE())) b 
ON a.offset = b.trannum
WHERE 
a.offset > 1 
AND b.trannum IS NULL
AND a.offset < @maxorder
ORDER BY Missing

提前致谢!

1 个答案:

答案 0 :(得分:1)

DECLARE @maxorder INT, @counter INT = 1 --Set this to your lower bound for SalesOrder table

SELECT @maxorder = MAX(CAST(TranNo AS INT))
FROM SalesOrder

CREATE TABLE #temp (TranNum INT)

WHILE @counter <= @maxorder
BEGIN
    INSERT INTO #temp (TranNum) values (@counter)
END

SELECT t.TranNum
FROM #temp t
LEFT OUTER JOIN SalesOrder s ON t.TranNum = CAST(s.TranNo AS INT)
WHERE s.TranNo is null
ORDER BY t.TranNum