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

在dbt的get_columns_in_relation函数中正确使用变量的方法

解决dbt中动态获取表列及遍历多表的问题

先说说你代码里的核心问题:

  • 别在jinja的{% %}代码块里嵌套{{ }},直接写变量名就行
  • adapter.get_columns_in_relation接收的是Relation对象,不是字符串,直接传字符串会报错,得先把数据集+表名转换成Relation类型

单个表的正确写法

根据你的表所属类型,选对应的方式构建Relation:

方式1:项目内模型用ref

如果表是你dbt项目里的模型:

{%- set table_name = 'orders' -%}
{%- set customer_dataset = customer.id -%}
{%- set target_relation = ref(customer_dataset, table_name) -%}
{%- set columns = adapter.get_columns_in_relation(target_relation) -%}

方式2:外部数据源用source

如果表是在dbt_project.yml或sources.yml里定义的外部数据源:

{%- set table_name = 'orders' -%}
{%- set customer_dataset = customer.id -%}
{%- set target_relation = source(customer_dataset, table_name) -%}
{%- set columns = adapter.get_columns_in_relation(target_relation) -%}

方式3:完全动态表用api.Relation.create

如果表不属于现有模型或已定义数据源,手动构建关系:

{%- set table_name = 'orders' -%}
{%- set customer_dataset = customer.id -%}
{%- set target_relation = api.Relation.create(
    database=target.database,  # 可替换为你的数据库名
    schema=customer_dataset,
    identifier=table_name
) -%}
{%- set columns = adapter.get_columns_in_relation(target_relation) -%}

遍历多个表的实现

定义要处理的表列表,循环遍历每个表获取列即可:

{# 定义要遍历的表集合,每个元素是(数据集名, 表名) #}
{%- set tables_to_scan = [
    ('customer_1', 'orders'),
    ('customer_2', 'orders'),
    ('customer_3', 'users')
] -%}

{%- for dataset, table in tables_to_scan -%}
    {%- set target_relation = api.Relation.create(
        database=target.database,
        schema=dataset,
        identifier=table
    ) -%}
    {%- set columns = adapter.get_columns_in_relation(target_relation) -%}
    
    {# 这里写你的列处理逻辑,比如打印列信息 #}
    {%- do log("表 " ~ dataset ~ "." ~ table ~ " 的列:", info=True) -%}
    {%- for col in columns -%}
        {%- do log("- " ~ col.name ~ " (" ~ col.data_type ~ ")", info=True) -%}
    {%- endfor -%}
{%- endfor -%}

如果是要遍历不同客户的同类型表,嵌套循环即可:

{# 假设你有客户列表和要扫描的表名列表 #}
{%- set customers = [{'id': 'customer_1'}, {'id': 'customer_2'}] -%}
{%- set table_names = ['orders', 'users'] -%}

{%- for customer in customers -%}
    {%- for table in table_names -%}
        {%- set target_relation = api.Relation.create(
            database=target.database,
            schema=customer.id,
            identifier=table
        ) -%}
        {%- set columns = adapter.get_columns_in_relation(target_relation) -%}
        
        {# 自定义处理逻辑 #}
        {%- do log("客户 " ~ customer.id ~ " 的表 " ~ table ~ " 列信息:", info=True) -%}
        {%- for col in columns -%}
            {%- do log(col.name ~ ": " ~ col.data_type, info=True) -%}
        {%- endfor -%}
    {%- endfor -%}
{%- endfor -%}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:20:23