I have the following code for a UDF but it errors with the message:
Msg 156, Level 15, State 1, Procedure CalendarTable, Line 39 Incorrect syntax near the keyword 'OPTION'.
is it because of my WITH statement as I can run the same code fine in a stored procedure?
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Anthony Main
-- Create date: 18/11/08
-- Description: Produce Table of Dates for Month
-- =============================================
CREATE FUNCTION CalendarTable
(
@StartDate DATETIME,
@EndDate DATETIME
)
RETURNS TABLE
AS
RETURN
(
with MyCalendar as
(
select cast(@StartDate as datetime) DateValue
union all
select DateValue + 1
from MyCalendar
where DateValue + 1 <= @EndDate
)
select DateValue
, datepart(dy, DateValue) [day of year]
, datename(dw, DateValue) [day]
, datepart(dw, DateValue-1) [day of week]
, datepart(dd, DateValue) [day of month]
, datepart(ww, DateValue) [week]
, datepart(mm, DateValue) [month]
, datename(mm, DateValue) [month]
, datepart(qq, DateValue) [quarter]
, datepart(yy, DateValue) [year]
, datepart(HH, DateValue) [HOUR]
, datepart(MI, DateValue) [MIN]
, datepart(SS, DateValue) [SEC]
, datepart(MS, DateValue) [MILLISECOND]
from MyCalendar
OPTION (MAXRECURSION 0)
)
GO