雪花循环遍历数组以运行存储过程

时间:2021-07-12 03:29:13

标签: javascript snowflake-cloud-data-platform

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

这是我目前所拥有的:



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 compilation error: 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))) ;'});' position 114

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

我知道我的数组有以下值 enter image description here

1 个答案:

答案 0 :(得分:1)

你应该对字符串使用双引号而不是单引号,并将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]] });
       
        }
$$;