【问题标题】:ORACLE output of logical comparison逻辑比较的ORACLE输出
【发布时间】:2020-04-18 15:42:26
【问题描述】:

我想在 oracle 中输出逻辑比较。在下面的示例中,输出应该是错误的,而不是抛出错误。我来自 sql server 世界,这很简单。在 oracle 中,这显然是完全不同的。

DECLARE
    test1 number := 1;
    test2 number := 2;
BEGIN
    dbms_output.put_line(test1 = test2);
END;

【问题讨论】:

    标签: sql oracle stored-procedures plsql


    【解决方案1】:

    您可以使用条件表达式:

    dbms_output.put_line(case when test1 = test2 then 1 else 0 end);
    

    Demo:

    dbms_output:
    0
    

    【讨论】:

    • 感谢演示。在这样的 oracle 查询中,begin - end 块是强制性的吗?
    • @FrenkyB:这实际上不是一个查询,而是一个匿名代码块,确实需要begin/end。
    【解决方案2】:

    仅供参考。几年来我没有写过任何严肃的 Oracle,但这个问题让我想起了一个我已经准备好的函数。它在没有交互式调试器的情况下进行非常方便的调试。以为我会分享它。

    create or replace function boolean_to_text(test_in boolean)
    return varchar2
    is
    begin
      return case when test_in then 'true' 
                  when not test_in then 'false' 
                  else 'null'
             end ; 
    end boolean_to_text;
    

    其中“test_in”是任何布尔表达式。它之所以有效,是因为在调用函数之前对表达式进行了评估。不幸的是,由于 Oracle 尚未在 SQL 中支持布尔数据类型,因此只能在 plsql 中使用。

    -- tests
    begin 
      dbms_output.put_line( '1=1 is ' || boolean_to_text(1=1) ); 
      dbms_output.put_line( '1=0 is ' || boolean_to_text(1=0) );   
      dbms_output.put_line( 'a>b is ' || boolean_to_text('a'>'b'));
      dbms_output.put_line( 'True>False ' || boolean_to_text(true>false) ); 
      dbms_output.put_line( 'Sysdate> 2020-05-18 is ' || boolean_to_text(Sysdate> date '2020-05-18') );   
      dbms_output.put_line( 'Null=Null is ' || boolean_to_text(null=null) );  
    end; 
    

    【讨论】:

      猜你喜欢
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-16
      • 2010-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多