首页 > 解决方案 > 雪花循环通过数组运行存储过程

问题描述

我创建了一个数组来存放我的存储过程参数。如何循环遍历数组,并将值作为参数输入到我的存储过程中?

这是我到目前为止所拥有的:

CREATE OR REPLACE PROCEDURE SP_TL_START()
RETURNS VARCHAR
LANGUAGE javascript
AS
$$
//Array created to house parameters. 
var report_users = [];

// create for the following users
var rs = snowflake.execute( { sqlText: 
`
SELECT 
DISTINCT USERS

    FROM USERS_TABLES
`} );

//load user values from table into Array,  we will be looping through the array to execute the store proc

while (rs.next()){
    var report_user_id = rs.getColumnValue(1);
    report_users.push(report_user_id);
                  }
//run store proc for each user - format for store proc = SP_TL_RUN(USERVALUE,DATE);                  

for (var i = 0; i < report_users.length; i++) {
        snowflake.execute( { sqlText: 'CALL SP_TL_RUN(report_users[i], TO_VARCHAR(SUBSTRING(DATEADD(DAY,-1,'2021-07-09'),1,10))) ;'});
       
        }
$$;
    
                                              
CALL SP_TL_START ()                                          

我收到以下错误:

JavaScript 编译错误:
Uncaught SyntaxError: Unexpected number in SP_TL_START at ' snowflake.execute( { sqlText: 'CALL SP_TL_RUN(report_users[i], TO_VARCHAR(SUBSTRING(DATEADD(DAY,-1,'2021-07-09'),1 ,10))) ;'});' 位置 114

我尝试遍历数组 (report_users) 并打印值,但 Snowflake 不允许我这样做console.log(report_users[i]),并且在我调用它时一直导致 null。

我知道我的数组具有以下值

在此处输入图像描述

标签: javascriptsnowflake-cloud-data-platform

解决方案


您应该对字符串使用双引号而不是单引号,并将 JS 变量作为绑定变量发送:

CREATE or replace PROCEDURE SP_TL_START()
RETURNS VARCHAR
LANGUAGE javascript
AS
$$
//Array created to house parameters. 
var report_users = [];

// create for the following users
var rs = snowflake.execute( { sqlText: 
`
SELECT 
DISTINCT USERS

    FROM USERS_TABLES
`} );

//load user values from table into Array,  we will be looping through the array to execute the store proc

while (rs.next()){
    var report_user_id = rs.getColumnValue(1);
    report_users.push(report_user_id);
                  }
//run store proc for each user - format for store proc = SP_TL_RUN(USERVALUE,DATE);                  

for (var i = 0; i < report_users.length; i++) {
        snowflake.execute( { sqlText: "CALL SP_TL_RUN(?, TO_VARCHAR(SUBSTRING(DATEADD(DAY,-1,'2021-07-09'),1,10))) ;", binds: [report_users[i]] });
       
        }
$$;

推荐阅读