oracle 创建一个 pl/sql 函数并找到闰年

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20947642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 02:09:42  来源:igfitidea点击:

Create a pl/sql function & find leap years

oracleplsql

提问by Aditya

Please let me know how to find a leap year through PL/SQL function. Suppose we input any number, how can we find out it is leap year or not?

请让我知道如何通过 PL/SQL 函数找到闰年。假设我们输入任何数字,我们如何知道它是不是闰年?

回答by Dba

Try the below function,

试试下面的功能,

FUNCTION leap_year_or_not(
         i_year IN NUMBER)
         RETURN VARCHAR2
IS
     l_var VARCHAR2(20);
BEGIN
     IF TO_CHAR(LAST_DAY(TO_DATE('01/02/'||i_year, 'dd/mm/yyyy')), 'DD') = 29 THEN
          l_var := 'Leap Year';
     ELSE
          l_var := 'Not Leap Year';
     END IF;
     RETURN l_var;                 
END;

回答by Nick Krasnov

Basically, if a year is divisible by 4 without a remainder and not by 100 it's a leap year. But, if the year is divisible by both 4 and 100 without a remainder, it also should be divisible by 400 to be a leap year.

基本上,如果一年可以被 4 整除而没有余数而不是 100,那么它就是闰年。但是,如果年份可以被 4 和 100 整除而没有余数,那么它也应该被 400 整除才能成为闰年。

So a function, which will tell you whether a year you've provided is a leap one or not could look like this:

所以一个函数,它会告诉你你提供的一年是否是一个闰年,它看起来像这样:

 create or replace package utl is
   function is_leap_year(p_year in number) return number;
 end;
/
Package created


create or replace package body utl is
  function is_leap_year(p_year in number) return number is
  begin
     return case
              when ( mod(p_year, 4) = 0 and mod(p_year, 100) <> 0 ) or
                   ( mod(p_year, 400) = 0 ) then 1
              else 0
            end;
  end;
end;
/
Package body created

Test case:

测试用例:

SQL> select 1999 + level                    as test_year
  2       , utl.is_leap_year(1999 + level)  as is_leap
  3    from dual
  4  connect by level <= 12
  5  ;

Result:

结果:

 TEST_YEAR    IS_LEAP
---------- ----------
      2000          1
      2001          0
      2002          0
      2003          0
      2004          1
      2005          0
      2006          0
      2007          0
      2008          1
      2009          0
      2010          0
      2011          0

12 rows selected