A View of Numbers

The below view will generate a list of numbers ranging from 1 - 4,294,967,296.  This view can be used in place of a physical table of numbers for some small operations but since it utilizes several large cross joins it is not very efficient once it starts counting into large numbers.

 

create view vw_Nums
as
with cte0 as (select 1 as c union all select 1),
cte1 as (select 1 as c from cte0 a, cte0 b),
cte2 as (select 1 as c from cte1 a, cte1 b),
cte3 as (select 1 as c from cte2 a, cte2 b),
cte4 as (select 1 as c from cte3 a, cte3 b),
cte5 as (select 1 as c from cte4 a, cte4 b),
nums as (select row_number() over (order by c) as n from cte5)
select n from nums
go

 

This view will be referenced for use in the user defined functions that we publish in case you don't have a numbers table


Posted 3/7/2009 12:35 AM by BrandonGalderisi

Comments

ssharathc wrote re: A View of Numbers
on 3/27/2009 5:48 AM

Can you explain the logic behind your CTEs?

TimChapman wrote re: A View of Numbers
on 3/27/2009 1:25 PM

Using the CTE's in this fashion allows for a quick "cartesion product, where the results are compounded for the previous CTE.  Using the ROW_NUMBER ranking function allows for the assignment of the incremental values.  Does that make sense?

Tip of the Week wrote The Numbers Table (Round 2)
on 4/27/2009 9:14 PM

Originally I wrote about The Numbers Table over at SQL Server Central . Over there I presented the structure

Copyright SQL Server Nation 2010
Powered by Community Server (Non-Commercial Edition), by Telligent Systems