【问题标题】:Snowflake UDF with variable number of inputs输入数量可变的 Snowflake UDF
【发布时间】:2022-12-05 23:13:04
【问题描述】:

我想将可变数量的输入传递给 Snowflake 中的以下 udf。

CREATE FUNCTION concat_ws_athena(s1 string, s2 string)
  returns string
  as 
  $$
  array_to_string(array_construct_compact(s1, s2), '')
  $$
  ;

你如何声明可变数量的输入?

简单地使用数组是行不通的:

CREATE FUNCTION concat_ws_athena(s array)
  returns string
  as 
  $$
  array_to_string(array_construct_compact(s), '')
  $$
  ;
  
SELECT concat_ws_athena('a', 'b')

【问题讨论】:

    标签: sql snowflake-cloud-data-platform


    【解决方案1】:

    如果你想准确模拟这条语句的输出:

    select array_to_string(array_construct_compact('a', 'b', 'c'), ',');
    

    如这里所见:

    那么你的函数应该是这样的:

    CREATE OR REPLACE FUNCTION concat_ws_athena(s array)
      returns string
      as 
      $$
      array_to_string(s, ',')
      $$
      ;
    

    你会这样称呼它:

    SELECT concat_ws_athena(['a', 'b', 'c']);
    

    不传递 2 个单独的参数,而是传递一个包含所有参数的数组。

    【讨论】:

    • 我的错:我应该指定我更愿意有一个不需要数组作为输入的解决方案,即没有[...],但更重要的是它仍然应该返回一个值,以防其中一个输入为空。这就是我使用 array_constract_compact 的原因。
    • 不支持可变数量的参数,因此您可能需要该数组。
    【解决方案2】:

    现在您无法定义具有可变数量输入参数的 UDF。你可以;但是,重载 UDF,以便您可以通过这种方式创建具有一组可变输入参数的 UDF。在切断过载的地方必须有一些合理的限制。例如,这里的重载允许 2、3 或 4 个参数。这个数字可能会更高。

    CREATE or replace FUNCTION concat_ws_athena(s1 string, s2 string)
      returns string
      called on null input
      as 
      $$
      array_to_string(array_construct_compact(s1, s2), '')
      $$
      ;
      
    CREATE or replace FUNCTION concat_ws_athena(s1 string, s2 string, s3 string)
      returns string
      called on null input
      as 
      $$
      array_to_string(array_construct_compact(s1, s2, s3), '')
      $$
      ;
      
    CREATE or replace FUNCTION concat_ws_athena(s1 string, s2 string, s3 string, s4 string)
      returns string
      called on null input
      as 
      $$
      array_to_string(array_construct_compact(s1, s2, s3, s4), '')
      $$
      ;
      
    select concat_ws_athena('one','two',null,'three');
    

    此外,如果任何输入参数为 null,大多数但不是所有 Snowflake 函数(包括 UDF)将立即返回 null。要覆盖 UDF 上的该行为,您可以在定义中指定 called on null input

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多