Is it possible in Snowflake dwh to retrive SQL query result and pass it as a variable to the next query within same procedure?
I'm trying to attempt %ROWCOUNT, CURSOR case and got stuck with below:
CREATE OR REPLACE PROCEDURE PASS_VAR_IN_JS() RETURNS VARCHAR LANGUAGE javascript AS $$ var command = "SELECT * FROM TABLE WHERE ATTRIBUTE = 'Value'"; var stmt = snowflake.createStatement( {sqlText: command} ); var result1 = stmt.execute(); return result1.getColumnName(3); //this returns column name var col_name = result1.getColumnName(3); //save column name to variable //pass the column name to the query var stmt = snowflake.createStatement({sqlText: "SELECT * FROM INFORMATION_SCHEMA WHERE COLUMN_NAME = ;", binds:[col_name]}); $$;
UPDATE - working code that passes one result to another query
<pre>
CREATE OR REPLACE PROCEDURE szpotma_rowcount()
RETURNS VARCHAR(250)
LANGUAGE JAVASCRIPT
as
$$
var command = `SELECT ATTR1 FROM TABLE1 LIMIT 1`;
var stmt = snowflake.createStatement( {sqlText: command} );
var rs = stmt.execute(), col_name ;
if (rs.next()) {
col_name = rs.getColumnValue(1);
stmt = snowflake.createStatement({
sqlText: `SELECT STATUS FROM TABLE_STATUS WHERE ATTR1 = :1`, binds: [col_name]});
//view second query results
rs = stmt.execute();
rs.next()
return rs.getColumnValue(1);
}
$$
Sure.
You can do with just:
var command = `SELECT * FROM TABLE WHERE ATTRIBUTE = 'Value'`;
var stmt = snowflake.createStatement( {sqlText: command} );
var rs = stmt.execute(), col_name ;
if (rs.next()) {
col_name = rs.getColumnValue(3);
stmt = snowflake.createStatement({
sqlText: `SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = :1`,
binds: [col_name]
});
}
I've listed up various ways to pull data from a result set in:
How to use Show Command in Stored Procedures - Not working
[Copied from above]:
If you have multiple columns, the code becomes slightly more complicated:
var result = [], row, col;
while (rs.next()) {
row = [];
for (col = 1; col <= stmt.columnCount; col++)
row.push(rs.getColumnValue(col));
result.push(row);
}
Hardcore JavaScript programmers might compress this to:
var result = [], cols = Array.from({ length: stmt.columnCount }, (v, i) => i + 1);
while (rs.next()) result.push(cols.map(c => rs.getColumnValue(c)));
A final variant where the first result row contains the column names and the following rows contain the data from the result set, accessible as result[row][column]:
var result =
[ Array.from({ length: stmt.columnCount }, (v, i) => stmt.getColumnName(i + 1)) ];
while (rs.next()) result.push(result[0].map(cn => rs.getColumnValue(cn)));