Select statements included within a function cannot return data to a client. FUNCTION SQL SERVER

TAII EL MEHDI 21 Reputation points
2020-08-18T11:20:45.207+00:00

CREATE FUNCTION Testing(@d1 DATE,@d2 DATE,@nd VARCHAR(MAX))
RETURNS int
WITH EXECUTE AS CALLER
AS
BEGIN
;with AllDates AS
(
SELECT @d1 AS DateOf
UNION ALL
SELECT DateAdd(day,1,DateOf)
FROM AllDates
WHERE DateOf<@d2
) select COUNT(*) SumOfDays FROM AllDates
WHERE NOT EXISTS(SELECT 1
FROM STRING_SPLIT(@nd,' ')
WHERE DATENAME(weekday,dateof) = value)

END;

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,589 questions
0 comments No comments
{count} votes

Accepted answer
  1. tibor_karaszi@hotmail.com 4,306 Reputation points
    2020-08-18T11:57:43.48+00:00

    You are trying to create a scalar function (RETURNS int). Such can only return one value using the RETURN command inside your function code.

    I have a feeling that you want to create a table function, to return a table (like a parameterized view, if such existed). Then you need to change your code to (untested):

    CREATE FUNCTION dbo.Testing(@d1 DATE, @d2 DATE, @nd VARCHAR(MAX))
    RETURNS TABLE
    AS
    RETURN(
        WITH AllDates AS
            (
                SELECT @d1 AS DateOf
                UNION ALL
                SELECT DateAdd(day,1,DateOf)
                FROM AllDates
                WHERE DateOf<@d2
            ) 
        select COUNT(*) SumOfDays 
        FROM AllDates
        WHERE NOT EXISTS(SELECT 1
        FROM STRING_SPLIT(@nd,' ')
        WHERE DATENAME(weekday,dateof) = value)
        )
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful