Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to create a function which will retrieve year, based on a certain logic

Status
Not open for further replies.

arkagopal

Programmer
Apr 10, 2019
1
0
0
US
I need to create a function in DB2 which will retrieve year from the current date, based on a certain logic

If the number of the month of the current date is smaller and equal than 6 (=any month prior to June) then the previous year is the ‘reference year’
Else if the number of the month of the current date is larger than 6 (=any month after June!) then the current year is the ‘reference year’.
Examples:

The reference year for date ‘4/9/2019’ is 2018 , since 4 <= 6
The reference year for date ‘9/3/2019’ is 2019, since 9 > 6
Below is an example for the implementation for SQL Server:

CREATE FUNCTION dbo.getReferenceYear()
RETURNS int
AS

BEGIN
DECLARE @ret int;
SELECT @ret = MONTH(GETDATE())

IF (@ret <= 6)
SET @ret = (YEAR(GETDATE()) -1);
Else
SET @ret = (YEAR(GETDATE()) );
RETURN @ret;
END;
I need the same in db2.

Below is what I have tried

CREATE FUNCTION dbo.getReferenceYear()
RETURNS INT
BEGIN ATOMIC

DECLARE _month INT;
DECLARE _year INT;

SET _month = SELECT MONTH (current timestamp) FROM sysibm.sysdummy1

if(_month<=6)
SET _year = (SELECT YEAR (current timestamp) FROM sysibm.sysdummy1) -1
ELSE
SET _year = (SELECT YEAR (current timestamp) FROM sysibm.sysdummy1)

RETURN _year
END
 
For example you can try something like this:
Code:
create or replace function getReferenceYear()
  returns decimal (4, 0)
  returns null on null input
begin  
  declare ref_year decimal (4, 0);

  set ref_year = year(current_date);
  if(month(current_date) <= [s][/s]6) then
    set ref_year = ref_year - 1;
  end if;
  return ref_year;
end

then this works
Code:
select current_date, getreferenceyear() from sysibm.sysdummy1
and gives this output
Code:
 ....+....1....+....2....+....3 
 CURRENT DATE  GETREFERENCEYEAR 
  2019-04-12         2018      
 ********  End of data  ********
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top