-2

I'm trying to make a function but I do not know how to get the WITH in it. Here is my code.

CREATE FUNCTION CubicVolume  (@StartDate date, @EndDate date) RETURNS @TableDays TABLE
(Days int)
AS
BEGIN
    INSERT @TableDays
       WITH Dates AS  (
                SELECT @StartDate AS DayInQuestion
                    UNION ALL
                SELECT DATEADD(Day, 1, DayInQuestion) AS DayInQuestion
                    FROM Dates AS Dates
                    WHERE (DayInQuestion < @EndDate)
                )
    SELECT DISTINCT count(Dates.DayInQuestion)
        FROM Dates AS Dates LEFT OUTER JOIN
        HEATHrs ON Dates.DayInQuestion = HEATHrs.StartDate
        WHERE        (CAST(DATEPART(weekday, Dates.DayInQuestion) AS int) BETWEEN 2 AND 6)
   RETURN
END
D Stanley
  • 149,601
  • 11
  • 178
  • 240

1 Answers1

2

You have to put the Common Table Expression (CTE) before the INSERT:

WITH Dates AS  
(
    SELECT @StartDate AS DayInQuestion
        UNION ALL
    SELECT DATEADD(Day, 1, DayInQuestion) AS DayInQuestion
        FROM Dates AS Dates
        WHERE (DayInQuestion < @EndDate)
)
INSERT @TableDays
SELECT DISTINCT count(Dates.DayInQuestion)
    FROM Dates AS Dates LEFT OUTER JOIN
    HEATHrs ON Dates.DayInQuestion = HEATHrs.StartDate
    WHERE        (CAST(DATEPART(weekday, Dates.DayInQuestion) AS int) BETWEEN 2 AND 6)
D Stanley
  • 149,601
  • 11
  • 178
  • 240