Snowflake - 为空行复制列 headers

Snowflake - copy column headers for empty row

我正在使用 copy into 命令将 snowflake 的查询结果存储到 s3 存储桶中的文件中。它按预期工作,但是当查询 returns 没有数据时,我仍然想将列名保存在同一个文件中,以便我可以在 UI 中显示带有列名的空行。我在命令中指定了 header=true 但是当查询 returns 没有结果时它不起作用。

谢谢

根据 docs:

If the source table contains 0 rows, then the COPY operation does not unload an empty data file; not even a file containing the table column headings.

而且似乎没有办法改变这种行为。

但是,在将 table 写入 S3 之前,您可以通过查询 INFORMATION_SCHEMA 来写入 header(作为数据)。然后像往常一样写你的table(OVERWRITE=TRUE)——如果没有行被写,header文件将保留。


更新

下面是如何生成 header:

select listagg(column_name,',') within group (order by ordinal_position)
from MY_DB.information_schema.columns 
where table_schema='MY_SCHEMA' and table_name='MY_TABLE';

然后您可以将其作为数据写入 CSV 文件,如下所示:

copy into @my_stage/my_table  (
    select listagg(column_name,',') 
        within group (order by ordinal_position)
    from MY_DB.information_schema.columns 
    where table_schema='MY_SCHEMA' and table_name='MY_TABLE';
)
file_format = (type=csv compression=none field_delimiter=none)
header=false;