Snowflake 中的存储过程:在 where 子句中使用参数

Stored Procedure in Snowflake: Use parameter in the where clause

我在 Snowflake 中有以下存储过程:

 create or replace procedure test_procedure(parameter varchar)
    returns number
    language sql
    as
    $$
    begin
    
        if ((SELECT MONTHLY_DELIVERED_AMOUNT FROM test.process.msv_month_amount where TARGET_KEY = parameter) = 0)
        then
            return null;
        else
            return (SELECT monthly_target_amount from test.process.msv_month_amount where TARGET_KEY = parameter);
        end if;
    end;
    $$
    ;
    
    
    call test_procedure('Key10');

当我尝试调用 test_procedure 时,出现以下错误:

 SQL compilation error: error line 1 at position 98 invalid identifier 'parameter'

我该如何解决这个问题?

带单冒号 (:) 的用户参数

create or replace procedure test_procedure(parameter varchar)
    returns number
    language sql
    as
    $$
    begin
    
        if ((SELECT MONTHLY_DELIVERED_AMOUNT FROM test.process.msv_month_amount where TARGET_KEY = :parameter) = 0)
        then
            return null;
        else
            return (SELECT monthly_target_amount from test.process.msv_month_amount where TARGET_KEY = :parameter);
        end if;
    end;
    $$
    ;
    
    
    call test_procedure('Key10');

您应该在变量名前加一个冒号。

create or replace procedure test_procedure(parameter varchar)
returns number
language sql
as
$$
begin

    if ((SELECT MONTHLY_DELIVERED_AMOUNT FROM msv_month_amount where TARGET_KEY = :parameter) = 0)
    then
        return null;
    else
        return (SELECT monthly_target_amount from msv_month_amount where TARGET_KEY = :parameter);
    end if;
end;
$$
;

call test_procedure('Key10');

下面提供了有关用法的文档链接

https://docs.snowflake.com/en/developer-guide/snowflake-scripting/variables.html#using-a-variable-in-a-sql-statement-binding

https://docs.snowflake.com/en/sql-reference/stored-procedures-snowflake-scripting.html#calling-a-stored-procedure-without-using-the-returned-value

代码可以简化为单个查询和CASE表达式:

SELECT CASE WHEN MONTHLY_DELIVERED_AMOUNT = 0 THEN NULL
            ELSE monthly_target_amount 
       END
FROM msv_month_amount 
WHERE TARGET_KEY = :parameter