- 利用 CTE 產生完整的流水號表,再去比對現有資料並找出最小流水號
DECLARE @Temp table (SeqNO smallint)
INSERT INTO @Temp VALUES(1)
INSERT INTO @Temp VALUES(3)
INSERT INTO @Temp VALUES(4)
INSERT INTO @Temp VALUES(9)
;
WITH CTE
AS
(
SELECT 1 AS SeqNO
UNION ALL
SELECT SeqNO + 1
FROM CTE
WHERE SeqNO < 5
)
SELECT MIN(T1.SeqNO) AS MinNO
FROM CTE AS T1
LEFT JOIN @Temp AS T2 ON T1.SeqNO = T2.SeqNO
WHERE T2.SeqNO IS NULL
此作缺點是跑 CTE 會耗費大量 CPU,流水號越多的情況下,此缺點會更明顯。
- 參考資料:
- 藍色小舖關於流水號建置討論文章
沒有留言:
張貼留言