Snowflake Stored Procedure While Function
Solution 1:
Snowflake supports expressing stored procedures in JavaScript
, and JavaScript
supports multiple looping constructs including while (condition)
.
A rough translation of the described logic as a Snowflake procedure would appear as follows:
CREATE OR REPLACE PROCEDURE looping_process()
RETURNS BOOLEAN
LANGUAGE JAVASCRIPT
AS
$$
// Get 'LastRow' dynamically, or set/pass a constant alternatively
var row_count_query = snowflake.createStatement({ sqlText: "SELECT * FROM SOURCE_TABLE" });
var _resultSet = row_count_query.execute();
var LastRow = row_count_query.getRowCount();
var counter = 0;
while (counter <= LastRow) {
// Get the dynamic date value by applying the counter
var seq_query = `SELECT SUNDAY::DATE AS "DateLoad" FROM "Staging"."Stg_EC_WeeksLoad" WHERE SEQUENCE = $counter`;
var seq_stmt = snowflake.createStatement({ sqlText: seq_query });
var seq_result = seq_stmt.execute(); seq_result.next();
var DateLoad = seq_result.getColumnValue("DateLoad");
// Construct and run the nested procedure call with value found above
var sub_call_query = `CALL "dbo"."pETLFillFact_Demographics_History"($DateLoad)`;
var sub_call_stmt = snowflake.createStatement({ sqlText: sub_call_query });
var sub_call_result = sub_call_stmt.execute(); sub_call_stmt.next();
var return_value = sub_call_result.getColumnValue(1);
// Increment for the next loop
counter += 1;
}
// (… add other omitted logic, to return/error-handle/etc. …)
$$
;