【问题标题】:How to Abort or Exit from Redshift Query with a conditional expression?如何使用条件表达式中止或退出 Redshift 查询?
【发布时间】:2019-08-21 23:48:36
【问题描述】:

我正在尝试使用 CASE 语句中止/退出基于条件表达式的查询:

  • 如果表有 0 行,那么查询应该会顺利进行。
  • 如果表的行数 > 0,则查询应中止/退出。
    drop table if exists #dups_tracker ;

    create table #dups_tracker
    (
      column1 varchar(10)
    );

    insert into #dups_tracker values ('John'),('Smith'),('Jack') ;

    with c1 as
    (select
         0 as denominator__v
        ,count(*) as dups_cnt__v
    from #dups_tracker
    )
    select
      case 
        when dups_cnt__v > 0 THEN 1/denominator__v
      else   
        1  
      end Ind__v
    from c1
    ;

这里是错误信息:

亚马逊无效操作:除以零; 1 条语句失败。

【问题讨论】:

  • 错误是由0 as denominator__v 引起的,然后尝试除以该值。它不会总是返回错误吗?
  • 感谢约翰的回复。这里真正的问题是,Redshift SQL 正在尝试首先解析 case 条件值,然后进行树遍历。由于查询失败,甚至没有评估 CASE 表达式。我的要求是如果计数(*)> 0,如何退出/中止查询。我的意思是如果表中有任何行,那么查询错误或中止它。希望这会有所帮助。

标签: amazon-web-services amazon-redshift


【解决方案1】:

没有中止 SQL 查询的概念。它要么编译成查询,要么不编译。如果它编译,查询就会运行。

最接近的选择是编写Stored Procedure,其中可以包含IF 逻辑。因此,它可以先查询一个表的内容,然后根据结果决定是否执行另一个查询。

【讨论】:

    【解决方案2】:

    这是我能够编写的逻辑,以在正面用例的情况下中止 SQL,

    /* Dummy Table to Abort Dups Check process if Positive */
    
    --Dups Table
    drop table if exists #dups;
    create table #dups
    (
      dups_col varchar(1)
    );
    insert into #dups values('A');
    
    --Dummy Table
    drop table if exists #dummy ;
    create table #dummy
    (
    dups_check decimal(1,0)
    )
    ;
    
    --When Table is not empty and has Dups
    insert into #dummy
    select 
    count(*) * 10
    from #dups
    ;
    
    /*
    [Amazon](500310) Invalid operation: Numeric data overflow (result precision)
    Details: 
     -----------------------------------------------
      error:  Numeric data overflow (result precision)
      code:      1058
      context:   64 bit overflow
      query:     3246717
      location:  numeric.hpp:158
      process:   padbmaster [pid=6716]
      -----------------------------------------------;
    1 statement failed.
    */
    
    
    --When Table is empty and doesn't have dups
    truncate #dups ;
    
    insert into #dummy
    select 
    count(*) * 10
    from #dups
    ;
    

    【讨论】:

      【解决方案3】:
      drop table if exists temp_table;
      create temp table temp_table (field_1 bool);
      
      insert into temp_table
          select  case
                      when false -- or true
                      then 1
                      else 1 / 0
                      end as field_1;
      

      这应该编译,当条件不满足时会失败。

      不知道为什么它与您的示例不同...

      编辑:以上内容在查询表时不起作用。留在这里留给后代。

      【讨论】:

      • 嗯...这似乎不适用于实际表格。我将把它留在这里作为一个警示故事。
      猜你喜欢
      • 2018-02-12
      • 2016-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多