You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Jinja函数在dbt模型中遇意外语法错误求助

解决方案与错误分析

错误原因解析

你提供的代码存在两个核心问题:

  1. 语法错误:循环生成列字段时未添加逗号分隔,最终SQL会变成select my_table.col1my_table.col2...的格式,数据库解析时遇到连续的.就会抛出语法错误。
  2. 逻辑不符需求:这段代码的作用是查询表的所有字段值,而非将列名本身提取到单个列中,和你的核心需求不匹配。

针对需求的实现方案

根据你“将所有列名提取到单个列”的需求,分两种常见场景给出实现:

场景1:将列名作为多行数据输出(一行对应一个列名)

通过循环生成union all语句,把每个列名作为单独的行返回:

{%- set table_cols = adapter.get_columns_in_relation(source('my_model_name', 'my_table')) -%}

select column_name
from (
    {% for col in table_cols %}
    select '{{ col.name }}' as column_name
    {% if not loop.last %}union all{% endif %}
    {% endfor %}
) as column_names_list

场景2:将所有列名拼接成字符串(单个列存储所有列名)

把所有列名用分隔符(比如逗号)拼接成一个字符串,放在单个列中:

{%- set table_cols = adapter.get_columns_in_relation(source('my_model_name', 'my_table')) -%}
{%- set joined_col_names = table_cols | map(attribute='name') | list | join(', ') -%}

select '{{ joined_col_names }}' as all_column_names

如果希望直接从数据库系统表获取列名(性能更优,尤其适用于大表),可以用对应数据库的系统视图查询,以Snowflake为例:

select listagg(column_name, ', ') within group (order by ordinal_position) as all_column_names
from information_schema.columns
where table_schema = '{{ source('my_model_name', 'my_table').schema }}'
  and table_name = '{{ source('my_model_name', 'my_table').name }}'

补充:若你实际需求是查询表的所有列

如果之前的代码是误写,你的真实需求是查询表的所有字段值,只需在循环中添加逗号分隔即可修复语法错误:

{%- set table_cols = adapter.get_columns_in_relation(source('my_model_name', 'my_table')) -%}

select
  {% for col in table_cols %}
  my_table.{{ col.name }}{% if not loop.last %},{% endif %}
  {% endfor %}
from {{ source('my_model_name', 'my_table') }}

内容的提问来源于stack exchange,提问作者jimiclapton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 00:27:08