if exists (select * from dbo.sysobjects where id = object_id(N'[f_GetNumbersTable]') and xtype in (N'FN', N'IF', N'TF'))
drop function [f_GetNumbersTable]
GO
/*
Purpose: Retun virtual table of integers within [@min, @max] range
Source: SQL Server magazine Jan 2007
*/
create function dbo.f_GetNumbersTable(@min as int, @max as int)
returns table as return
--//------------------------------------------------- Non-Recursive Query
--//--- The code defines a CTE called C0, which returns two rows with a single
--//--- column called const that holds a constant value. Here,
--//--- the CTE�s purpose is simply to generate two rows;
--//--- it doesn�t really matter what those rows contain.
--//--- Then a series of CTEs (C1, C2, C3, C4, C5, ...) double the rows...
with
C0 as (select 0 as const --//--- 2 rows
union all
select 0),
C1 as (select 0 as const --//--- 4 rows
from C0 as A,
C0 as B),
C2 as (select 0 as const --//--- 16 rows
from C1 as A,
C1 as B),
C3 as (select 0 as const --//--- 256 rows
from C2 as A,
C2 as B),
C4 as (select 0 as const --//--- 65536 rows
from C3 as A,
C3 as B),
C5 as (select 0 as const --//--- 4,294,967,296 rows
from C4 as A,
C4 as B),
/*
C6 as (select 0 as const --//--- 18,446,744,073,709,551,616 rows
from C5 as A,
C5 as B),
*/
Product as (
select TOP(@max) ROW_NUMBER() OVER(ORDER BY const) AS n
from C5--C6
)
Select n
from Product
where n >= @min;
Go