Thursday, January 26, 2012

CTE - Generate Sequence

WITH Nbrs ( n ) AS (

        SELECT 1 UNION ALL
        SELECT 1 + n FROM Nbrs WHERE n < 500 )
    SELECT n FROM Nbrs
    OPTION ( MAXRECURSION 500 )

with DateCTE as
(
    select cast('2012-01-01' as datetime) DateValue
    union all
    select DateValue + 1
    from    DateCTE  
    where   DateValue + 1 < GETDATE()
)
select DateValue
 from    DateCTE
 OPTION (MAXRECURSION 0)

with DateCTE as
(
    select cast('2012-01-01 00:00:00' as datetime) DateValue
    union all
    select dateadd(hh, 1, DateValue)
    from    DateCTE  
    where   dateadd(hh, 1, DateValue) < GETDATE() + 1
)
select DateValue
 from    DateCTE
 OPTION (MAXRECURSION 0)

Generate Sequence from a Range


;with cte as
(
      select Id, StartIp, EndIP, StartIp as Ip
      from Subnets
union all
      select Id, StartIp, EndIP, Ip + 1 as Ip
      from cte where Ip + 1 <= EndIP
)
select * from cte
order by id
OPTION ( MAXRECURSION 5000 


No comments:

Post a Comment