雪花存储过程,同时起作用

时间:2020-01-24 23:08:07

标签: sql function loops stored-procedures snowflake-cloud-data-platform

如何在雪花示例中重新创建while函数:

WHILE @counter <= @LastRow
     BEGIN
        SELECT @DateLoad = CONVERT (date, SUNDAY)
        FROM [Staging].[Stg_EC_WeeksLoad]
        WHERE SEQUENCE = @counter;

        EXEC @return_value = [dbo].[pETLFillFact_Demographics_History] @Date = @DateLoad;

        SET @counter = @counter + 1;
    END

2 个答案:

答案 0 :(得分:2)

雪花支持expressing stored procedures in JavaScriptJavaScript支持multiple looping constructs,包括while (condition)

将所描述的逻辑粗略地解释为雪花程序,如下所示:

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. …)
$$
;

答案 1 :(得分:0)

WHILE特定语法的示例(来自Snowflake文档)如下所示:

while (condition)  {
   // Do something ...
   }