Skip to content

Instantly share code, notes, and snippets.

@jonasraoni
Last active February 24, 2019 11:28
Show Gist options
  • Save jonasraoni/7cef8cc40011b734c9c7d9583d8919ac to your computer and use it in GitHub Desktop.
Save jonasraoni/7cef8cc40011b734c9c7d9583d8919ac to your computer and use it in GitHub Desktop.
Fill the gaps in SQL Server
/*
There is a table in database. This table contains unduplicated natural numbers. There may be gaps in the sequence of natural numbers in the table. You need to output missing numbers.
Table of natural numbers: declare @values as table ([number] int not null).
Test data: insert into @values([number]) values (1), (2), (3), (5), (9).
Result: declare @missing as table ([left] int not null, [right] int not null).
*/
DECLARE @values AS TABLE ([number] INT NOT NULL);
INSERT INTO @values([number]) VALUES (1), (2), (3), (5), (9);
DECLARE @missing AS TABLE ([left] INT NOT NULL, [right] INT NOT NULL)
INSERT INTO @missing
SELECT v.number + 1, next.number - 1
FROM
@values v
LEFT JOIN @values next
ON next.number = (
SELECT TOP 1
tmp.number
FROM
@values tmp
WHERE
tmp.number > v.number
)
WHERE
v.number + 1 <> next.number
ORDER BY
v.number
/*
Alternative style...
DECLARE @values AS TABLE ([number] INT NOT NULL);
INSERT INTO @values([number]) VALUES (1), (2), (3), (5), (9);
DECLARE @missing AS TABLE ([left] INT NOT NULL, [right] INT NOT NULL)
-- Keeps the previous and next numbers
DECLARE @previous AS INTEGER, @next AS INTEGER;
-- Fast forward cursor to find the holes
DECLARE rsValues CURSOR FAST_FORWARD FOR
SELECT number
FROM @values
ORDER BY number;
OPEN rsValues;
-- Saves the first number
FETCH NEXT FROM rsValues INTO @previous;
WHILE @@FETCH_STATUS = 0
BEGIN
-- Gets the next number
FETCH NEXT FROM rsValues INTO @next;
-- If the next number is breaking the sequence, logs the hole to the @missing table
IF @@FETCH_STATUS = 0 AND @previous + 1 <> @next
INSERT INTO @missing VALUES (@previous + 1, @next - 1);
-- Updates the last number
SET @previous = @next;
END;
CLOSE rsValues;
DEALLOCATE rsValues;
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment