vrijdag 23 november 2012

How to list the last N years?

Sometimes we are required to facilitate a select list, from which a user can select the last, say 25 years (including the current year). Instead of defining a reference-table `YEARS', we have to maintain, we can define a SQL query using the CONNECT BY function. Here is how:
 
select to_char(sysdate,'YYYY') - level + 1 
from dual 
connect by level <= 25

Ofcourse the 25 in the above example is arbitrary, one could just instead use a package constant or some function.

In Oracle APEX, when defining this in a select list, it is tempting to write the following code:

 
select 
  to_char(sysdate,'YYYY') - level + 1 display
, to_char(sysdate,'YYYY') - level + 1 return
from dual 
connect by level <= apex_constants.g_list_years

From a maintainability perspective one should consider implementing a shared component LOV based on the following query:
 
select 
   years display
 , years return
from (
      select 
       to_char(sysdate,'YYYY') - level + 1 years
      from dual 
      connect by level <= apex_helper_functions.list_number_of_years
     )

The `list_number_of_years' function would preferably make use of a APEX session-state value - when defined -, to give maximal flexibility in a given page.

Once defined in this manner, you will hopefully agree the list is easy to maintain.

[update 26-11-2012]
A carefull reader noticed (thanks JL!) that using the Oracle EXTRACT function would shave off one implicit conversion, resulting in a better performance (EXTRACT returns a NUMBER instead of VARCHAR2, so when doing - LEVEL + 1 Oracle doesn't have to convert to NUMBER). Here is the code:

 
select 
   years display
 , years return
from (
      select 
       extract(year from sysdate) - level + 1 years
      from dual 
      connect by level <= apex_helper_functions.list_number_of_years
     )
Always open for suggestions! Thanks JL!

Geen opmerkingen:

Een reactie posten