Hi Geoff. Long time no see.
First, create this function. It's a "programmable" Tally function.
CREATE FUNCTION [dbo].[fnTallyProg]
/**********************************************************************************************************************
Purpose:
Given a start value, end value, and increment, create a sequencial list of integers.
Programmers Notes:
1. The increment can be negative if the start value is greater than the end value.
Revison History:
Rev 00 - 18 Feb 2017 - Jeff Moden
- Initial creation and unit test.
**********************************************************************************************************************/
(
@pStart BIGINT
,@pEnd BIGINT
,@pIncrement BIGINT
)
RETURNS TABLE WITH SCHEMABINDING AS
RETURN WITH
E01(N) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))E0(N)) --10 rows
,E04(N) AS (SELECT 1 FROM E01 a CROSS JOIN E01 b CROSS JOIN E01 c CROSS JOIN E01 d) --10 Thousand rows
,E16(N) AS (SELECT 1 FROM E04 a CROSS JOIN E04 b CROSS JOIN E04 c CROSS JOIN E04 d) --10 Quadrillion rows, which is crazy
SELECT TOP (ABS((@pEnd-@pStart+@pIncrement)/@pIncrement))
N = (ROW_NUMBER() OVER (ORDER BY (SELECT NULL))-1)*@pIncrement+@pStart
FROM E16
WHERE (@pStart<=@pEnd AND @pIncrement > 0)
OR (@pStart>=@pEnd AND @pIncrement < 0)
;
GO
After that and using your good test data, the problem becomes trivial.
SELECT t.Id
,Continuous = s.N
FROM #T t
CROSS APPLY dbo.fnTallyProg(t.StartSeqNo,t.EndSeqNo,1) s
;
--Jeff Moden
Change is inevitable... Change for the better is not.