我试图从我的dbt模型中的表中选择所有列名到sql表中的单个列。我希望这样做的原因是,我相信这是一种可扩展的方式,可以列出所有列名,而不管表的大小如何,表的大小可能从10个到几十个不等。
我正在使用adapter.get_columns_in_relation
函数和for
循环,我已经看到许多来源描述的方法,包括StackOverflow。
我的代码如下;
{%- set table_cols = adapter.get_columns_in_relation(source('my_model_name', 'my_table')) -%}
select
{% for col in table_cols %}
my_table.{{col.name}}
{% endfor %}
from
{{source('my_model_name', 'my_table')}}
我看不出为什么这不应该工作,但是我得到的错误是…
Server error: Database Error in rpc request (from remote system)
001003 (42000): SQL compilation error:
syntax error line 5 at position 31 unexpected '.'.
我将非常感激任何帮助或建议更好的方法来实现我的目标。
您正在寻找的方法可能如下所示:
{%- set table_cols = adapter.get_columns_in_relation(source('your_schema', 'your_table')) -%}
select distinct
-- concatenate column names gathered in table_cols in a single column within a comma-separated string
{% for col in table_cols %}
'{{ col.name }}'
{% if not loop.last -%} || ', ' || {% endif -%}
{% endfor %} as cols_list
from {{ source('your_schema', 'your_table') }}
上面的代码^创建了一个模型,该模型将源表的所有不同列名收集到单个列中。由于我使用了distinct
,因此输出将是单行,列名之间用逗号(,)分隔。请看下面的输出示例:
| cols_list |
|--------------------------------------------------------|
| id, customer_id, first_name, last_name, address, email |
当您检查编译的SQL时,您的方法的问题是可见的:您只是调用列名,而没有任何函数来捕获列名内的不同名称。查看下面代码中编译的SQL示例:
select
col1 col2 col3 col4 col5 [...]
from your_db.your_schema.your_table