雪花循环通过数组运行存储过程
Posted
技术标签:
【中文标题】雪花循环通过数组运行存储过程【英文标题】:Snowflake loop through array to run stored procedure 【发布时间】:2021-07-12 03:29:13 【问题描述】:我创建了一个数组来存放我的存储过程参数。如何循环遍历数组,并将值作为参数输入到我的存储过程中?
这是我目前所拥有的:
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 编译错误: 未捕获的 SyntaxError:SP_TL_START 中的意外数字' 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。
我知道我的数组有以下值
【问题讨论】:
【参考方案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]] );
$$;
【讨论】:
以上是关于雪花循环通过数组运行存储过程的主要内容,如果未能解决你的问题,请参考以下文章