我需要将一个表的列名插入另一个表。
这是我的尝试:
我首先创建了一个表以插入列名
create or replace table TABLE1 (tab_name string, col_name string);
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));
}
//Values not being inserted into the table
for(i=0; i<cols.length;i++)
{
var stmt2 = snowflake.createStatement({
sqlText: "INSERT INTO TABLE1 VALUES(" + TABLE_NAME + "," + cols[i] + ")" + ";"
});
stmt2.execute();
}
return cols
$$;
当我打印出TABLE1时,没有得到任何输出。我不明白我在哪里做错了
答案 0 :(得分:1)
当我执行您的存储过程(假设TABLE_NAME = FOO)时,它返回错误:
Execution error in store procedure GET_COLUMNS: SQL compilation error: error line 1 at position 26 invalid identifier 'FOO' At Statement.execute, line 18 position 15
如果查看“ SQL历史记录”,将会看到正在生成以下INSERT语句:
INSERT INTO TABLE1 VALUES(FOO,COL1);
缺少字面值周围的单引号;应该是:
INSERT INTO TABLE1 VALUES('FOO','COL1');
要纠正此问题,您可以更改此内容:
var stmt2 = snowflake.createStatement({
sqlText: "INSERT INTO TABLE1 VALUES(" + TABLE_NAME + "," + cols[i] + ")" + ";"
});
对此:
var stmt2 = snowflake.createStatement({
sqlText: "INSERT INTO TABLE1 VALUES('" + TABLE_NAME + "','" + cols[i] + "')" + ";"
});
话虽如此,我将完全从另一个角度进行研究。检索元数据信息(例如列名)的更有效方法是通过INFORMATION_SCHEMA视图。如果您不需要将列名称的数组作为存储过程的输出返回,则可以使用以下方法:
CREATE OR REPLACE PROCEDURE get_columns(TABLE_NAME VARCHAR)
RETURNS ARRAY
LANGUAGE JAVASCRIPT
AS
$$
let sql_insert = `
INSERT INTO TABLE1 (
tab_name
,col_name
)
SELECT TABLE_NAME
,COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ?
`;
snowflake.execute({"sqlText" : sql_insert, "binds" : [TABLE_NAME]});
return [];
$$
;
如果您确实要求存储过程在输出数组中返回列名,那么您可以使用如下代码:
CREATE OR REPLACE PROCEDURE get_columns(TABLE_NAME VARCHAR)
RETURNS ARRAY
LANGUAGE JAVASCRIPT
AS
$$
let sql_get_cols = `
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = ?
ORDER BY ORDINAL_POSITION
`;
let sql_insert = `
INSERT INTO TABLE1 (
tab_name
,col_name
)
VALUES (?, ?)
`;
let rs_get_cols = snowflake.execute({"sqlText" : sql_get_cols, "binds" : [TABLE_NAME]});
let cols = [];
while (rs_get_cols.next()) {
let column_name = rs_get_cols.getColumnValue(1);
snowflake.execute({"sqlText" : sql_insert, "binds" : [TABLE_NAME, column_name]});
cols.push(column_name);
}
return cols;
$$
;
在这方面还有其他变化。