Q:

Using Recursive query in function

I have this query developed with the help of a guy here and I am not able to use this in function. 
There is some sort of Syntax issue. 
Here is the query 
WITH CTE AS (
    SELECT @STARTDATE AS STARTDATE
    UNION ALL
    SELECT DATEADD(D,1,STARTDATE) 
    FROM CTE
    WHERE STARTDATE <@ENDDATE
),
WORKINGDAYS AS (
    SELECT STARTDATE,
           DATENAME(DW,STARTDATE)WEEKDAYS,
           C1.CalanderDayName AS isweekend
    FROM CTE c
         LEFT JOIN HRM.tbl_Calendar C1 ON DATENAME(DW,STARTDATE) = C1.CalanderDayName
                                      AND C1.IsOffDay = 1
)

SELECT COUNT(WEEKDAYS)as WORKINGDAYS
FROM WORKINGDAYS
WHERE isweekend IS NULL;

I want to create a function named fnGetWorkingDays
ALTER FUNCTION [dbo].[fnGetWorkingDays] (@StartDate datetime, @EndDate datetime)
RETURNS int
AS
BEGIN
     DECLARE @dateFrom datetime 
     DECLARE @dateTo datetime 
     SET @dateFrom = @StartDate 
     SET @dateTo = @EndDate

     DECLARE @WORKDAYS INT
     SELECT @WORKDAYS =

;WITH CTE AS (
SELECT @STARTDATE  AS STARTDATE
UNION ALL
select DATEADD(D,1,STARTDATE) 
FROM CTE
WHERE STARTDATE <@ENDDATE
)
,WORKINGDAYS AS (
SELECT STARTDATE,DATENAME(DW,STARTDATE)WEEKDAYS, C1.CalanderDayName AS isweekend
FROM CTE c
LEFT JOIN HRM.tbl_Calendar C1 ON DATENAME(DW,STARTDATE)=C1.CalanderDayName AND C1.IsOffDay=1
)

SELECT COUNT(WEEKDAYS)as WORKINGDAYS FROM WORKINGDAYS WHERE isweekend is null

     RETURN @WORKDAYS
END

A:

Try With this Below function .let me know back for any errors
CREATE FUNCTION [dbo].[fnGetWorkingDays] (@StartDate datetime, @EndDate datetime)
RETURNS int
AS
BEGIN 

     DECLARE @WORKDAYS INT

;WITH CTE AS (
    SELECT @STARTDATE AS STARTDATE
    UNION ALL
    SELECT DATEADD(D,1,STARTDATE) 
    FROM CTE
    WHERE STARTDATE <@ENDDATE
),
WORKINGDAYS AS (
    SELECT STARTDATE,
           DATENAME(DW,STARTDATE)WEEKDAYS,
           C1.CalanderDayName AS isweekend
    FROM CTE c
         LEFT JOIN HRM.tbl_Calendar C1 ON DATENAME(DW,STARTDATE) = C1.CalanderDayName
                                      AND C1.IsOffDay = 1
)

SELECT @WORKDAYS=COUNT(WEEKDAYS) FROM WORKINGDAYS WHERE isweekend is null

     RETURN @WORKDAYS
END

