Skip to content

Instantly share code, notes, and snippets.

@justinpitts
Created December 14, 2011 20:21
Show Gist options
  • Save justinpitts/1478332 to your computer and use it in GitHub Desktop.
Save justinpitts/1478332 to your computer and use it in GitHub Desktop.
t-sql function to generate a series of integers
--Attribution is due elsewhere; I didn't come up with this.
CREATE function dbo.generate_series
(
@pStartValue int = 1,
@pEndValue int = 1000000
)
returns table
as
return
(
with rows16(N) as
(
select 1 union all
select 1 union all
select 1 union all
select 1 union all
select 1 union all
select 1 union all
select 1 union all
select 1 union all
select 1 union all
select 1 union all
select 1 union all
select 1 union all
select 1 union all
select 1 union all
select 1 union all
select 1
),
rows256(N) as
(
select t1.N from rows16 t1 cross join rows16 t2
),
rows65536(N) as
(
select t1.N from rows256 t1 cross join rows256 t2
),
rows2pow32(N) as
(
select t1.N from rows65536 t1 cross join rows65536 t2
),
Numbers(N) as
(
select row_number() over (order by N) as N from rows2pow32 t1
)
select N from Numbers
where N between @pStartValue AND @pEndValue
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment