简体   繁体   English

如何在Snowflake中将表的列名存储在数组中

[英]How to store the column names of a table in an array in Snowflake

I am very new to Snowflake.我对雪花很陌生。 I need to retrieve only the column names of a table and then return it as an array in a stored procedure.我只需要检索表的列名,然后在存储过程中将其作为数组返回。

Example:例子:

   Column_A    Column_B    Column_C    Column_D
      1           2           2           2

should return [ Column_A, Column_B, Column_C, Column_D]应该返回 [Column_A, Column_B, Column_C, Column_D]

Here is my attempt:这是我的尝试:

create or replace procedure sample()
    return RETURNTYPE?
    language javascript
    AS
    $$
      var cmd = 'SELECT COLUMN_NAME' FROM table1;
      var statement = snowflake.createStatement({sqlTest: cmd});
      var res = statement.execute();
      var arr = [];
      //HOW CAN I PUSH COLUMN NAMES INTO THIS ARRAY
      
      return ARRAY;

    $$;

I new to this.我对此很陌生。 Can someone explain how to solve this.有人可以解释如何解决这个问题。

I would simply leverage information_schema and the array_agg() function to get this done, rather than a stored procedure.我会简单地利用information_schemaarray_agg()函数来完成这项工作,而不是使用存储过程。 Something like this works without all of the javascript as a native function in Snowflake:像这样的东西在没有所有 javascript 作为 Snowflake 中的本机函数的情况下工作:

SELECT array_agg(column_name)
FROM information_schema.columns
where table_name = 'TABLE_NAME';

Check Mike Walton's solution that doesn't use stored procedures.查看 Mike Walton 的不使用存储过程的解决方案。 Leaving this answer up for anyone looking for an answer with stored procedures.将此答案留给任何寻找存储过程答案的人。


One solution is to run a SELECT * within the stored procedure, and then the statement will have the name of the columns:一种解决方案是在存储过程中运行SELECT * ,然后语句将具有列的名称:

CREATE OR REPLACE PROCEDURE get_columns(TABLE_NAME VARCHAR)
RETURNS ARRAY
LANGUAGE JAVASCRIPT
AS
$$
var stmt = snowflake.createStatement({
    sqlText: "SELECT * FROM " + TABLE_NAME + " LIMIT 1;",    
});
stmt.execute();

var cols=[];
for (i = 1; i <= stmt.getColumnCount(); i++) {
  cols.push(stmt.getColumnName(i));
}
return cols
$$
;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM