Snowflake Syntax when passing array into insert query

Viewed 283

My code obtains the column list of a table I have created the attributes of this table are the contextual values of a session in snowflake such as USER,DATABASE,WAREHOUSE...ETC Afterwards it places those attribute names into an array I then try to call on these names in making an insert query and this is where I am struggling with the syntax

Because each value in my array is USER, DATABASE,WAREHOUSE I am trying to call on the context functions like CURRENT_WAREHOUSE() Can someone please help me with the syntax

    for(i=0;i<arr.length;i++){
        v_sqlCode = `INSERT INTO SESSION_ATTRIBUTES( arr[i] )
                        "VALUES ("CALL CURRENT_"+arr[i]+"()")';    
    }
1 Answers

You can't directly use the output of a Snowflake stored procedure programmatically. If you need to use the output value, you have to collect it using the RESULT_SCAN table function. That can get a bit complex to handle, directly in code, so it's far better to place it into a helper function. See this example of one SP calling another one and using its output value. It does this by calling the SP using the callSP helper function. Use the entire SQL statement including the call command into the SQL parameter for that function. It will run the SP, grab the result from the result_scan table function and return it.

create or replace procedure HELLO_WORLD()
returns string
language javascript
as
$$
    return "Hello, world.";
$$;

create or replace procedure CALL_HELLO_WORLD()
returns string
language javascript
execute as caller
as
$$

return callSP(`call HELLO_WORLD()`);

// ---- Main function above, helper functions below.

function callSP(sql){
    let cmd = {sqlText: sql};
    let stmt = snowflake.createStatement(cmd);
    stmt.execute();
    let result_scan  = `select $1 from table(result_scan(last_query_id()));`;
    let result_cmd   = {sqlText: result_scan};
    let result_stmt  = snowflake.createStatement(result_cmd);
    let rs           = stmt.execute();
    if(rs.next()) {
        return rs.getColumnValue(1);
    } else {
        return null;
    }
}

$$;

call call_hello_world();
Related