only My site

Friday, February 29, 2008

Oracle PL/SQL Leap year & Cheatsheet

A year is considered a leap year if the year is divisible by 4 but not divisible by 100 unless also divisible by 400.
create or replace function IS_LEAP_YEAR (nYr in number) return boolean is
v_day varchar2(2);
begin
select to_char(last_day(to_date( '01-FEB-' to_char(nYr), 'DD-MON-YYYY')), 'DD') into v_day from dual;
if v_day = '29' then -- if v_day = 29 then it must be a leap year, return TRUE
return TRUE;
else
return FALSE; -- otherwise year is not a leap year, return false
end if;
end;

--Or we can use Mod(year,4)
/*
V_REMAINDER1 := MOD(nYear,4);
V_REMAINDER2 := MOD(nYear,100);
V_REMAINDER3 := MOD(nYear,400);
IF ((V_REMAINDER1 = 0 AND V_REMAINDER2 <> 0 ) OR V_REMAINDER3 = 0) THEN
DBMS_OUTPUT.PUT_LINE(nYear ' is a leap year');
return true;
ELSE
DBMS_OUTPUT.PUT_LINE (nYear ' is not a leap year');
return false; */

Cheat sheet
http://www.yagc.ndo.co.uk/cheatsheets/plsql_cheatsheet.html

No comments: