【问题标题】:Retrieving table name from snowflake information_schema using dbt使用 dbt 从雪花 information_schema 中检索表名
【发布时间】:2021-07-11 02:34:55
【问题描述】:

我创建了一个宏来从 Snowflake 中的 INFORMATION_SCHEMA 返回一个表名。

我在雪花中有如下表格

------------
|  TABLES  |
------------
|   ~one   |
|   ~two   |
|  ~three  |
------------

我想将表格类型(即one)传递给宏并获取实际的表格名称,即~one

这是我在 DBT 中的宏(get_table.sql),它接受参数并返回表名

{%- macro get_table(table_type) -%}
    
    {%- set table_result -%}
        select distinct TABLE_NAME from "DEMO_DB"."INFORMATION_SCHEMA"."TABLES" where TABLE_NAME like '\~%{{table_type}}%'
    {%- endset -%}
    
    {%- set table_name = run_query(table_result).columns[0].values() -%}
  
  {{ return(table_name) }}
{%- endmacro -%}

这是我调用上述宏的 DBT 模型

{{ config(materialized='table',full_refresh=true) }}

select * from {{get_table("one")}}

但我收到一个错误:

模型编译错误

'None' 没有属性'table'

> 在宏 get_table (macros\get_table.sql)

我不明白错误在哪里

【问题讨论】:

    标签: sql snowflake-cloud-data-platform dbt


    【解决方案1】:

    您需要使用执行上下文变量来防止此错误,如下所述:

    https://discourse.getdbt.com/t/help-with-call-statement-error-none-has-no-attribute-table/602

    你还要小心你的查询,表名是大写的。所以你最好用“ilike”而不是“like”。

    还有一点很重要,“run_query(table_result).columns[0].values()”返回的是一个数组,所以我在末尾添加了索引。

    这是你的模块的修改版本,我在我的测试环境中成功运行它:

    {% macro get_table(table_name) %}
        
        {% set table_query %}
            select distinct TABLE_NAME from "DEMO_DB"."INFORMATION_SCHEMA"."TABLES" where TABLE_NAME ilike '%{{ table_name }}%'
        {% endset %}
    
        {% if execute %}
            {%- set result = run_query(table_query).columns[0].values()[0] -%}
            {{return( result )}}
        {% else %}
            {{return( false ) }}
        {% endif %}
        
    {% endmacro %}
    

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 2022-08-04
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多