-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFindMissingNumbers.sql
More file actions
43 lines (35 loc) · 809 Bytes
/
Copy pathFindMissingNumbers.sql
File metadata and controls
43 lines (35 loc) · 809 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
Purpose:
- Find gaps between the minimum and maximum numeric key in a table.
Safety:
- Read-only. Large key ranges can be expensive; narrow the range when appropriate.
Requirements:
- SQL Server 2012 or later.
Customization:
- Replace dbo.SampleRecords and record_id.
*/
DECLARE @MinimumValue BIGINT;
DECLARE @MaximumValue BIGINT;
SELECT
@MinimumValue = MIN(record_id),
@MaximumValue = MAX(record_id)
FROM dbo.SampleRecords;
;WITH Numbers AS
(
SELECT @MinimumValue AS value
WHERE @MinimumValue IS NOT NULL
UNION ALL
SELECT value + 1
FROM Numbers
WHERE value < @MaximumValue
)
SELECT n.value AS missing_value
FROM Numbers AS n
WHERE NOT EXISTS
(
SELECT 1
FROM dbo.SampleRecords AS r
WHERE r.record_id = n.value
)
ORDER BY n.value
OPTION (MAXRECURSION 0);