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

如何在dates_list为空时跳过dbt增量模型的创建?

解决dbt增量模型在dates_list为空时报错的问题

方案一:生成合法空结果集SQL

当dates_list为空时,输出一个返回空结果的合法查询,避免数据库因空SQL语句报错。修改后的模型代码如下:

-- depends_on: {{ref('stg_table')}}
{% set dates_query %}
SELECT DISTINCT date FROM dates_table
{% if is_incremental() %}
WHERE date NOT IN (SELECT DISTINCT date FROM {{this}})
{% endif %}
{% endset %}

{% set dates_res = run_query(dates_query) %}

{% if execute %}
{# Return the first column #}
{% set dates_list = dates_res.columns[0].values() %}
{% else %}
{% set dates_list = [] %}
{% endif %}

{% if dates_list %}
with
{% for date in dates_list %}
prel_{{date | replace('-', '_')}} as (
  SELECT smth FROM {{ref('stg_table')}}
  WHERE some_date = cast('{{date}}' as date)
),
{% endfor %}
prel AS ( 
select * from prel_{{dates_list[0] | replace('-', '_')}}
{% for date in dates_list[1:] %}
union all
select * from prel_{{date | replace('-', '_')}}
{% endfor %}
)
SELECT some_transformations FROM prel

{% else %}
-- 无新日期需要处理时返回空结果集
SELECT * FROM {{ref('stg_table')}} WHERE 1=0
{% endif %}

方案二:终止模型构建(可选)

如果希望在无新数据时直接终止模型构建流程,可在else分支中抛出编译错误:

-- depends_on: {{ref('stg_table')}}
{% set dates_query %}
SELECT DISTINCT date FROM dates_table
{% if is_incremental() %}
WHERE date NOT IN (SELECT DISTINCT date FROM {{this}})
{% endif %}
{% endset %}

{% set dates_res = run_query(dates_query) %}

{% if execute %}
{# Return the first column #}
{% set dates_list = dates_res.columns[0].values() %}
{% else %}
{% set dates_list = [] %}
{% endif %}

{% if dates_list %}
with
{% for date in dates_list %}
prel_{{date | replace('-', '_')}} as (
  SELECT smth FROM {{ref('stg_table')}}
  WHERE some_date = cast('{{date}}' as date)
),
{% endfor %}
prel AS ( 
select * from prel_{{dates_list[0] | replace('-', '_')}}
{% for date in dates_list[1:] %}
union all
select * from prel_{{date | replace('-', '_')}}
{% endfor %}
)
SELECT some_transformations FROM prel

{% else %}
{% do raise_compiler_error('无新日期数据需要处理,终止模型构建') %}
{% endif %}

方案说明

  • 方案一不会中断dbt运行流程,模型会生成空视图/表,后续依赖该模型的任务可正常执行(读取空数据)。
  • 方案二会直接终止当前模型构建,适合不需要保留空模型的场景,但会导致dbt运行状态标记为失败,需根据实际需求选择。

内容的提问来源于stack exchange,提问作者Артем Сысуев

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:25:28