Search code examples
sqluser-defined-functionsscalargetdate

How to resolve error with SQL Scalar variable using GETDATE


I'm writing a scalar variable in SQL to define a season year (which starts halfway through a calendar year). It needs to change as the date changes i.e. 2021 for this date, on June 1 2022 then it should change to 2022.

It's generating this error code:

"Error referencing function 'GETDATE': non-deterministic, security and metadata function calls are not allowed in user-defined functions."

I can’t see any workarounds online that can deal with the issue in detail. Any ideas?

The code is:

CREATE FUNCTION CDP.fn_SeasonYear
(
)
RETURNS INT
       AS 
       BEGIN
              DECLARE @ThisSeason INT
       SET @ThisSeason = 
       CASE
              WHEN DatePart(Month, GETDATE()) < 6
              THEN CONVERT(int,DatePart(Year, GETDATE()) -1)
              ELSE CONVERT(int,DatePart(Year, GETDATE()))
       End

RETURN @ThisSeason
END;

Solution

  • This is not ideal but it's an approach I've used. As mentioned, functions are required to return the same value given the same input. You pass getdate() as a parameter to the function.

    CREATE FUNCTION dbo.fn_SeasonYear( @currdate datetime )
    
    RETURNS INT
           AS 
           BEGIN
                  DECLARE @ThisSeason INT
           SET @ThisSeason = 
           CASE
                  WHEN DatePart(Month, @currdate) < 6
                  THEN CONVERT(int,DatePart(Year, @currdate) -1)
                  ELSE CONVERT(int,DatePart(Year, @currdate))
           End
    
    RETURN @ThisSeason
    END;