Assign result from stored procedure to a variable

Viewed 26

I have created a stored procedure that returns a create table sql statement; I want to be able to now call that procedure and assign the result to a variable like:

set create_table_statement = call sp_create_stage_table(target_db, table_name);

snowflake will not let me do this, so is there a way I can.

Context

We have just been handed over our new MDP which is built on AWS-S3, DBT & Snowflake, next week we go into production but we have 200+ tables and snowlpipes to code out. I wanted to semi automate this by generating the create table statements based off the tables metadata and then calling the results from that to create the tables. At the moment we're having to run the SQL, copy+paste the results in and then run that, which is fine in dev/pre-production mode when it's a handful of tables. but with just 2 of us it will be a lot of work to get all those tables and pipes created.

2 Answers

so I've found a work around, by creating a second procedure and calling the first one as a se=ql string to get the results as a string - then calling that string as a sql statement. like:

create or replace procedure sp_create_stage_table("db_name" string, "table_name" string)
returns string
language javascript
as
$$
    var sql_string = "call sp_get_create_table_statement('" + db_name + "','" + table_name + "');";
    var get_sql_query = snowflake.createStatement({sqlText: sql_string});
    var get_result_set = get_sql_query.execute();
    get_result_set.next();
    
    var get_query_value = get_result_set.getColumnValue(1);
    
    sql_string = get_query_value.toString();
    
    try {
        var main_sql_query = snowflake.createStatement({sqlText: sql_string});
        main_sql_query.execute();
        return "Stage Table " + table_name + " Successfully created in " + db_name + " database."
    }
    
    catch (err){
        return "an error occured! \n error_code: " + err.code + "\n error_state: " + err.state + "\n error_message: " + err.message;
    }
    
$$;

It is possible to assign scalar result of stored procedure to session variable. Instead:

SET var = CALL sp();

The pattern is:

SET var = (SELECT * FROM TABLE(RESULT_SCAN(LAST_QUERY_ID())));

Sample:

CREATE OR REPLACE PROCEDURE TEST()
RETURNS VARCHAR
LANGUAGE SQL
AS
BEGIN
   RETURN 'Result from stored procedrue';
END;


CALL TEST();

SET variable = (SELECT * FROM TABLE(RESULT_SCAN(LAST_QUERY_ID())));

SELECT $variable;
-- Result from stored procedrue
Related