Sunday, September 25, 2005

emulated mssql dateadd and datediff function to postgresql: note only month is implemented

-- Function: dateadd(varchar, int4, date)

-- DROP FUNCTION dateadd("varchar", int4, date);

CREATE OR REPLACE FUNCTION dateadd("varchar", int4, date)
RETURNS date AS
$BODY$

DECLARE
p_Interval ALIAS FOR $1;
p_N ALIAS FOR $2;
p_Date ALIAS FOR $3;




BEGIN
if p_Interval = 'm' then
return p_Date + cast(p_N || ' months' as interval);
else
raise exception 'dateadd interval parameter not supported';
-- raise exception 'hello';
return null;
end if;
END;
$BODY$
LANGUAGE 'plpgsql';




-- Function: datediff(varchar, date, date)

-- DROP FUNCTION datediff("varchar", date, date);

CREATE OR REPLACE FUNCTION datediff("varchar", date, date)
RETURNS int4 AS
$BODY$

DECLARE
p_Interval ALIAS FOR $1;
p_DateFrom ALIAS FOR $2;
p_DateTo ALIAS FOR $3;




BEGIN
if p_Interval = 'm' then
return ((date_part('y',p_DateTo) * 12) + date_part('month',p_DateTo))
- ((date_part('y',p_DateFrom) * 12) + date_part('month',p_DateFrom));
else
raise exception 'Datediff: Interval not supported';
return 0;
end if;
END;
$BODY$




-- Function: datename(varchar, date)

-- DROP FUNCTION datename("varchar", date);

CREATE OR REPLACE FUNCTION datename("varchar", date)
RETURNS "varchar" AS
$BODY$

declare
p_DatePart ALIAS FOR $1;
p_Date ALIAS FOR $2;

BEGIN
IF p_DatePart = 'm' THEN
RETURN
CASE DATE_PART('month',p_Date)
WHEN 1 THEN 'January'
WHEN 2 THEN 'Feburary'
WHEN 3 THEN 'March'
WHEN 4 THEN 'April'
WHEN 5 THEN 'May'
WHEN 6 THEN 'June'
WHEN 7 THEN 'July'
WHEN 8 THEN 'August'
WHEN 9 THEN 'September'
WHEN 10 THEN 'October'
WHEN 11 THEN 'November'
WHEN 12 THEN 'December'
END;
ELSE
RAISE EXCEPTION 'Datename: date part not supported';
RETURN NULL;
END IF;

END;
$BODY$
LANGUAGE 'plpgsql' ;

0 Comments:

Post a Comment

<< Home