如何创建一个解析日期的函数

How to create a function that parses dates

您好,我有以下代码来创建一个函数。基本上它解析日期并根据日期告诉我整数。

CREATE OR ALTER FUNCTION VITAL_TARGET.roundfind(dates date)
 RETURNS varchar
 
AS

BEGIN


case 
    when dates between '2020-06-08' and '2020-11-14' then return 'Round 1'
    when dates between '2020-11-15' and '2021-02-17' then return 'Round 2'
    when dates between '2021-02-18' and '2021-04-28' then return 'Round 3'
    when dates between '2021-04-29' and '2021-07-16' then return 'Round 4'
    when dates between '2021-07-16' and '2021-10-03' then return 'Round 5'
    when dates between '2021-10-04' and '2021-11-30' then return 'Round 6'
    when dates between '2021-12-01' and '2022-02-01' then return 'Round 7'
    when dates between '2021-02-02' and '2022-03-28' then return 'Round 8'
    when dates >= '2022-03-29' then return 'Round 9'
end;

出现以下错误:

Msg 102, Level 15, State 1, Procedure roundfind, Line 1 [Batch Start Line 0]
Incorrect syntax near 'dates'.
Msg 178, Level 15, State 1, Procedure roundfind, Line 18 [Batch Start Line 0]
A RETURN statement with a return value cannot be used in this context.

你的功能有很多。首先,您将参数定义为一个名为 dates 的列, 而不是 一个参数 (@dates)。接下来您将 FUNCTION 定义为 return一个varchar(1),意味着它只会returnNULL'R'.

然后你有 CASE 表达式,它有标量值的语句; return 'Round 1' 不是标量值,它是语句。顾名思义,CASE 表达式是一个 表达式,因此它 return 是一个标量值,而不是语句或布尔结果。

在您的 CASE 表达式中,您还尝试再次引用列 dates,该列不存在,因为它没有任何内容(没有 FROM) .

您还缺少一个 END,无论是您的 CASE 表达式还是您的 BEGIN:

CREATE OR ALTER FUNCTION VITAL_TARGET.roundfind (@dates date)
RETURNS varchar(7)
AS
BEGIN
    RETURN CASE WHEN @dates BETWEEN '2020-06-08' AND '2020-11-14' THEN 'Round 1'
                WHEN @dates BETWEEN '2020-11-15' AND '2021-02-17' THEN 'Round 2'
                WHEN @dates BETWEEN '2021-02-18' AND '2021-04-28' THEN 'Round 3'
                WHEN @dates BETWEEN '2021-04-29' AND '2021-07-16' THEN 'Round 4'
                WHEN @dates BETWEEN '2021-07-16' AND '2021-10-03' THEN 'Round 5'
                WHEN @dates BETWEEN '2021-10-04' AND '2021-11-30' THEN 'Round 6'
                WHEN @dates BETWEEN '2021-12-01' AND '2022-02-01' THEN 'Round 7'
                WHEN @dates BETWEEN '2021-02-02' AND '2022-03-28' THEN 'Round 8'
                WHEN @dates >= '2022-03-29' THEN 'Round 9'
           END;
END;

但是,您可以使用以下内容使您的 CASE 表达式更加简洁:

CREATE OR ALTER FUNCTION VITAL_TARGET.roundfind (@dates date)
RETURNS varchar(7)
AS
BEGIN
    RETURN CASE WHEN @dates >= '2022-03-29' THEN 'Round 9'
                WHEN @dates >= '2021-02-02' THEN 'Round 8'
                WHEN @dates >= '2021-12-01' THEN 'Round 7'
                WHEN @dates >= '2021-10-04' THEN 'Round 6'
                WHEN @dates >= '2021-07-16' THEN 'Round 5'
                WHEN @dates >= '2021-04-29' THEN 'Round 4'
                WHEN @dates >= '2021-02-18' THEN 'Round 3'
                WHEN @dates >= '2020-11-15' THEN 'Round 2'
                WHEN @dates >= '2020-06-08' THEN 'Round 1'     
           END;
END;