-- IBM Confidential
-- OCO Source Materials
-- 5724-I68.
-- (C) Copyright IBM Corp. 2000, 2004 - All Rights Reserved.
-- US Government Users Restricted Rights - Use, duplication or disclosure
-- restricted by GSA ADP Schedule Contract with IBM Corp.

-- DB2 UDB UDF
--
-- Author    Kaustubh, Tushar
--
-- Usage of UDF:
-- convertdateformat (timestamp, varchar(20))
-- 
-- Synopsis : Return the date in the formats
--	      1. DD-MON-YYYY
--	      2. MON-YYYY
--	      3. MM-DD-YYYY
--  Similar functionality as to_char() in oracle. But this fuction returns only
--  for the specified three formats
--

-- Cleanup

drop function convertdateformat (timestamp, varchar(20));

create function convertdateformat(TS timestamp, fmt varchar(20)) 
returns varchar(50) 
NO EXTERNAL ACTION DETERMINISTIC 
return 
with tmp_mod (dd,mm,mon,yyyy,hh,mi,ss,nnnnnn) as 
( 
    select 
    substr( digits (day(TS)),9), 
    substr( digits (month(TS)),9) , 
    substr( MONTHNAME(TS), 1, 3),
    rtrim(char(year(TS))) , 
    substr( digits (hour(TS)),9), 
    substr( digits (minute(TS)),9), 
    substr( digits (second(TS)),9), 
    rtrim(char(microsecond(TS))) 
    from sysibm.sysdummy1
    ) 
select 
case fmt 
    when 'DD-MON-YYYY' 
        then dd ||'-'|| mon ||'-'|| yyyy 
    when 'MON-YYYY' 
        then  mon ||'-'|| yyyy 
    when 'MM-DD-YYYY' 
        then mm ||'-'|| dd ||'-'|| yyyy
    when 'dd-MON-YYYY' 
        then dd ||'-'|| mon ||'-'|| yyyy 
    when 'MM-dd-YYYY' 
        then mm ||'-'|| dd ||'-'|| yyyy

    else 
        'date format ' || coalesce(fmt,' <null> ') ||  
        ' not recognized.' 
    end 
from tmp_mod;

commit;

terminate;
