【问题标题】:Checking of current system date in static table检查静态表中的当前系统日期
【发布时间】:2022-01-11 03:38:36
【问题描述】:

我是 pl/sql 块的新手..我的 proc 中有如下要求:

我有一个静态数据表 tb_calender,其列 extract_dateDATE 类型。想要检查当前系统日期是否存在于表 tb_calender.extract_date 中。如果不存在,则退出记录错误的过程。

请就此提出建议。

【问题讨论】:

    标签: oracle function date stored-procedures plsql


    【解决方案1】:

    一个函数可能更合适(这样你就可以让调用者知道今天的日期是否存在于表中)。你可以返回一个布尔值,或者例如一个数字(更简单,因为您可以在 SQL 中使用它,而 Boolean 仅在 PL/SQL 中有效)。

    您可能不想检查sysdate 本身,因为它包含日期和时间组件(最多几秒),所以...该表包含匹配的值的可能性有多大现在时间>?这就是我使用TRUNC 函数的原因。

    设置:

    SQL> alter session set nls_date_Format = 'dd.mm.yyyy hh24:mi:ss';
    
    Session altered.
    
    SQL> select * from tb_calender;
    
    EXTRACT_DATE
    -------------------
    10.01.2022 00:00:00        --> that's today's date
    08.01.2022 00:00:00
    
    SQL> select sysdate from dual;
    
    SYSDATE
    -------------------
    10.01.2022 20:34:42
    

    功能:

    SQL> create or replace function f_test_01
      2    return number
      3  is
      4    /* Return 1 if EXTRACT_DATE which is equal to today's date exists.
      5       Return 0 otherwise
      6    */
      7    l_cnt number;
      8  begin
      9    select count(*)
     10      into l_cnt
     11      from tb_calender
     12      where extract_date = trunc(sysdate);
     13
     14    return case when l_cnt = 0 then 0
     15                else 1
     16           end;
     17  end f_test_01;
     18  /
    
    Function created.
    
    SQL> select f_test_01 from dual;
    
     F_TEST_01
    ----------
             1
    

    程序:

    SQL> create or replace procedure p_test
      2  is
      3    l_cnt number;
      4  begin
      5    select count(*)
      6      into l_cnt
      7      from tb_calender
      8      where extract_date = trunc(sysdate);
      9
     10    if l_cnt = 0 then
     11       dbms_output.put_line('Today''s date does not exist');
     12    else
     13       dbms_output.put_line('Today''s date exists');
     14    end if;
     15  end;
     16  /
    
    Procedure created.
    
    SQL> set serveroutput on
    SQL> exec p_test;
    Today's date exists
    
    PL/SQL procedure successfully completed.
    
    SQL>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      相关资源
      最近更新 更多