SQL Server : Option Clause in Views

I had a task to create MasterCalendar view which will return all the dates within a range. Here is the simplified query that needs to be included the view :


If you run the above create view statement, sql server will throw the following error:

Incorrect syntax near the keyword ‘option’.

It throws error because views do not allow option clauses. So the workaround would be to create the view without the option clause and when you call the view include the option clause as below:


Here is the code from the screen shot:
create view vw_MasterCalendar
with cte(N) as
select    cast('20120101' as datetime) as N
union all
select    cte.N + 1
from    cte
where    cte.N < cast('20130101' as datetime)
select    N as [Date]
from cte
select * from vw_MasterCalendar option (maxrecursion 1000)

SQL Server : Recursive CTE (Hierarchy Example)

create table #temp
id int,
name varchar(30),
parent_id int

insert #temp ( id, name, parent_id )
values  ( 1, 'A', null )
, ( 2, 'B', null )
, ( 3, 'C', null )
, ( 4, 'AA', 1 )
, ( 5, 'BB', 2 )
, ( 6, 'AAA', 4 )
, ( 7, 'AAAA', 6 )

select * from #temp


;with cte (id,name,parent)
select id, name,cast('' as varchar(30)) as parent
from #temp
where parent_id is null

union all

select c1.id,c1.name,c2.name as parent
from #temp c1
join cte c2 on c1.parent_id = c2.id

select id,name,parent from cte


SQL Server : Recursive CTE and Maximum Recursion

Default maximum recursion is 100. This can be altered by setting the maxrecursion as an option. If the recursion has gone past the maximum then you will receive the following error:

The statement terminated. The maximum recursion 100 has been exhausted before statement completion.

Here is an example with maximum recursion set to 1000.

;with cte(N) as
select 1 as N
union all
select cte.N + 1
from cte
where cte.N <1000
select * from cte
option (maxrecursion 1000)