How to use a case statement in scalar valued function in SQL?

前端 未结 6 1457
半阙折子戏
半阙折子戏 2020-12-31 04:26

I want to get one value from a function using a case statement. I tried the following but it does not work:

CREATE FUNCTION [FATMS].[fnReturnByPeriod]
(

            


        
6条回答
  •  情歌与酒
    2020-12-31 05:05

    Here's a SET based approach to write your function in SQL Server 2008

    CREATE FUNCTION [FATMS].[fnReturnByPeriod]
    (
        @Period INT
    )
    RETURNS int
    AS
    BEGIN
        return isnull((SELECT min(v)
        from (values
         (1,1),
         (7,2),
         (30,3),
         (90,4),
         (180,5),
         (360,6)) t(n,v)
        where n >= @Period and @period>0), 0)
    END
    

    The way you have written it, all the CASE branches return 1, so you might as well use

    return case when @period between 1 and 360 then 1 else 0 end
    

提交回复
热议问题