Search code examples
sqlsql-servert-sqlsql-server-2012-express

SQL Function returns no results, but function content returns results


I have the following SQL function definition and test:

IF EXISTS (SELECT *
       FROM   sys.objects
       WHERE  object_id = OBJECT_ID(N'[dbo].[udf_Assessment_Timelines]')
              AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
  DROP FUNCTION [dbo].udf_Assessment_Timelines
GO 
CREATE FUNCTION dbo.udf_Assessment_Timelines
(
    @startDate datetime, 
    @endDate datetime,
    @assessmentId int = 14,
    @outIds nvarchar(max)='3,9,10'
)
RETURNS @result TABLE(case_id int, [TOTAL DAYS] int)
AS
BEGIN
    DECLARE @in TimeLineReportList;
    DECLARE @out TimeLineReportList;

    INSERT INTO @in
       SELECT * FROM dbo.udf_First_Timeline_Entries_Of_Status(@assessmentId)

    INSERT INTO @out
       SELECT * FROM dbo.udf_First_Timeline_Entries_Of_Any_Statuses(@outIds)

    INSERT INTO @result
        SELECT * FROM dbo.udf_Generic_Timelines(@startDate, @endDate, @in, @out,null)

    RETURN
END
GO

SELECT * FROM dbo.udf_Assessment_Timelines('2013-01-01T00:00:00.000', '2014-01-01T00:00:00.000',null,null)

The final line that calls the function returns 0 rows. However, the below SQL returns rows when just executed directly. What's the difference?

DECLARE @result TABLE(case_id int, [TOTAL DAYS] int)    
DECLARE @in TimeLineReportList;
DECLARE @out TimeLineReportList;

INSERT INTO @in
   SELECT * FROM dbo.udf_First_Timeline_Entries_Of_Status(14)

INSERT INTO @out
   SELECT * FROM dbo.udf_First_Timeline_Entries_Of_Any_Statuses('3,9,10')

INSERT INTO @result
    SELECT * FROM dbo.udf_Generic_Timelines('2013-01-01T00:00:00.000', '2014-01-01T00:00:00.000', @in, @out,null)

SELECT * FROM @result

Solution

  • You're overriding @assessmentId and @outIds to be null in the version that doesn't work.

    SELECT * FROM dbo.udf_Assessment_Timelines('2013-01-01T00:00:00.000', 
        '2014-01-01T00:00:00.000', null, null)
                                   ^     ^
    

    If you want to use the default values for those parameters, use the default keyword instead:

    SELECT * FROM dbo.udf_Assessment_Timelines('2013-01-01T00:00:00.000', 
        '2014-01-01T00:00:00.000', default, default)
                                   ^        ^