pythonsqlsnowflake-cloud-data-platform

Get an output from a Python function in Snowflake SQL


I have the following code, which is supposed to return the value "Procedure executed successfully" into the my_var variable, but it's give me an error message that reads

"Syntax error: unexpected 'INTO'. (line 17) syntax error line 7 at position 2 unexpected 'RETURN'. (line 17)"

CREATE OR REPLACE TEMPORARY PROCEDURE my_python_proc()
RETURNS STRING
LANGUAGE PYTHON
RUNTIME_VERSION = 3.11
HANDLER = 'run'
AS
$$
def run():
    return "Procedure executed successfully"
$$
;

DECLARE my_var STRING;

BEGIN
  //LET my_var := CALL my_python_proc();
  EXECUTE IMMEDIATE 'CALL my_python_proc()' INTO :my_var;
  -- Use the variable, for example:
  RETURN my_var;
END;

Show VARIABLES;

Am I doing something wrong?

I am expecting the "my_var" variable to be set to "Procedure executed successfully"


Solution

  • EXECUTE IMMEDIATE is used for dynamic SQL and it is completely unnecessary in this context. You can use:

    CREATE OR REPLACE TEMPORARY PROCEDURE my_python_proc()
    RETURNS STRING
    LANGUAGE PYTHON
    RUNTIME_VERSION = 3.11
    PACKAGES = ('snowflake-snowpark-python')
    HANDLER = 'run'
    AS
    $$
    def run():
        return "Procedure executed successfully :)"
    $$
    ;
    

    Main query:

    DECLARE 
      my_var STRING;
    BEGIN
      -- option 1 using direct assignment
      my_var := (CALL my_python_proc());
    
      -- option 2 using CALL INTO
      CALL my_python_proc() INTO :my_var;
    
      RETURN :my_var;
    END;
    

    Output:

    enter image description here

    Side note: SHOW VARIABLES is for session variables which are different from Snowflake Scripting variables.