在 Snowflake 中创建带有变量的视图

问题描述 投票:0回答:3

我有以下观点:

create or replace view my_database_name.my_schema_name.d_dates as (

  /*
      Declare variables
  */
    set (start_date) = ('2017-07-01');
    set (end_date) = ('2022-06-30');

  /*
  */
  with part_1 as (

    select top 20000
        -1 + row_number() over(order by 0) as i_value
        , start_date + i_value as generated_date 
    from 
        (
            select 
                cast($start_date as date) as start_date
               ,cast($end_date as date) as end_date
        )
    inner join table
        (generator(rowcount => 100000 )) x
    /*
      Qualify filters the results of window functions
    */
    qualify 
        i_value < 1 + end_date - start_date

  )

  select
      (a.i_value + 1) as "date_id"
      ,a.generated_date as "date"
  from
      part_1 as a
  order by
      "date";
    

)

我收到以下错误消息:

SQL compilation error: syntax error line 6 at position 4 unexpected 'set'. syntax error line 6 at position 21 unexpected '='.

关于如何解决这个问题有什么建议吗?

sql view snowflake-cloud-data-platform
3个回答
1
投票

您可以使用表函数(UDTF)实现问题中描述的内容 开始和结束日期将是函数的参数。

CREATE OR REPLACE FUNCTION my_database_name.my_schema_name.d_dates (start_date date, end_date date)
RETURNS TABLE (date_id number, generated_date date)
LANGUAGE SQL
AS
'
with part_1 as (

    select top 20000
        -1 + row_number() over(order by 0) as i_value
        , start_date + i_value as generated_date 
    from 
        (
            select 
                cast(start_date as date) as start_date
               ,cast(end_date as date) as end_date
        )
    inner join table
        (generator(rowcount => 100000 )) x
    /*
      Qualify filters the results of window functions
    */
    qualify 
        i_value < 1 + end_date - start_date

  )

  select
      (a.i_value + 1) as date_id
      ,a.generated_date as generated_date
  from
      part_1 as a
  order by
      2;
'
;

Your SQL needs more tweaking I think like not using date as a column name but this should work

0
投票

Snowflake 中的视图无法承载变量设置或参数化。 但是,您可以通过使用用户定义的表函数(使用 SQL 或 Javascript)来实现您的目标:

https://docs.snowflake.com/en/sql-reference/udf-table-functions.html https://docs.snowflake.com/en/sql-reference/udf-js-table-functions.html


0
投票

另一种方法是将变量放入表(Temp、CTE)中,并根据所需条件将其连接到查询。

© www.soinside.com 2019 - 2024. All rights reserved.