【注意】最后更新于 October 31, 2022,文中内容可能已过时,请谨慎使用。
在dbt处理数据的时候,经常遇到需要将时间变为一个变量,以供不同时间跑数
方案: dbt var参数+macros
定义变量
编辑 dbt_project.yml
1
2
|
vars:
"start_date": 20221030
|
定义函数
1
2
3
4
5
6
7
8
9
10
11
12
|
CREATE OR REPLACE FUNCTION f_start_date(in p_date int)
RETURNS date
AS $$
DECLARE
BEGIN
if p_date=-1 then
return current_date;
else
return to_date(p_date::varchar,'yyyyMMdd');
end if;
END;
$$ LANGUAGE plpgsql;
|
定义macros
1
2
3
|
{% macro start_date() %}
{{target.schema}}.f_start_date({{var("start_date",-1)}})
{% endmacro %}
|
在脚本中使用
1
|
select {{start_date()}}
|
运行命令 dbt run
或者 dbt run --vars '{"start_date": 20210101}'