用户定义的标量函数与case表达式的语法不正确

时间:2014-08-08 00:00:17

标签: sql-server case user-defined-functions

我尝试了一些变体,但我无法正确理解这种语法:

CREATE FUNCTION [dbo].[ComputeNextDate] 
( 
    @pInputDate    DATETIME 
    , @Interval    VARCHAR(20)

)
RETURNS DATETIME
BEGIN

DECLARE @vOutputDate        DATETIME

SELECT 
    CASE @vOutputDate 
        When @Interval = 'Weekly' Then DATEADD(WEEK, 1, @pInputDate)
        When @Interval = 'Yearly' Then DATEADD(YEAR, 1, @pInputDate)
END


RETURN @vOutputDate

END

这是解析器返回的内容,我很困惑:

Msg 102, Level 15, State 1, Procedure ComputeNextDate, Line 15
Incorrect syntax near '='.
Msg 102, Level 15, State 1, Procedure ComputeNextDate, Line 22
Incorrect syntax near 'END'.

2 个答案:

答案 0 :(得分:2)

您正在混合case表达式的两种不同语法,使用其中一种语法。您还需要在select中进行分配才能将值输入变量:

SELECT
  @vOutputDate =
    CASE
        When @Interval = 'Weekly' Then DATEADD(WEEK, 1, @pInputDate)
        When @Interval = 'Yearly' Then DATEADD(YEAR, 1, @pInputDate)
END

或:

SELECT 
  @vOutputDate =
    CASE @Interval
        When 'Weekly' Then DATEADD(WEEK, 1, @pInputDate)
        When 'Yearly' Then DATEADD(YEAR, 1, @pInputDate)
END

答案 1 :(得分:1)

只是为了完成上一个答案,您可以在使用没有select语句的情况下设置输出变量,如下所示:

CREATE FUNCTION [dbo].[ComputeNextDate] 
    ( 
        @pInputDate    DATETIME 
        , @Interval    VARCHAR(20)

    )
    RETURNS DATETIME
    BEGIN

    DECLARE @vOutputDate        DATETIME

    SET @vOutputDate = CASE  
                        When @Interval = 'Weekly' Then DATEADD(WEEK, 1, @pInputDate)
                        When @Interval = 'Yearly' Then DATEADD(YEAR, 1, @pInputDate)
                   END


    RETURN @vOutputDate

END