1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| CREATE OR REPLACE FUNCTION "public"."trunc"("p_timestamp" timestamptz, "p_formart" varchar='DD'::character varying) RETURNS "pg_catalog"."timestamp" AS $BODY$ declare v_timestamp timestamp := null; v_formart varchar(10) := upper(p_formart); begin
if p_timestamp is not null then if v_formart in ('YYYY', 'YEAR') then v_timestamp := date_trunc('year', p_timestamp); elsif v_formart in ('MONTH', 'MON', 'MM', 'RM') then v_timestamp := date_trunc('month', p_timestamp); elsif v_formart in ('DD', 'DAY', 'DY') then v_timestamp := date_trunc('day', p_timestamp); elsif v_formart = 'D' then v_timestamp := (date_trunc('WEEK', p_timestamp) - interval'1 day'); elsif v_formart in ('W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7') then v_timestamp := date_trunc('WEEK', p_timestamp)::date + substr(v_formart, 2, 1)::integer - 2; elsif v_formart ~ '^D\+?[0-9]*$' then if substr(v_formart, 2, length(v_formart)-1)::integer between 1 and 366 then v_timestamp := date_trunc('year', p_timestamp)::date + substr(v_formart, 2, length(v_formart)-1)::integer - 1; if date_trunc('year', v_timestamp)::date > date_trunc('year', p_timestamp)::date then v_timestamp := date_trunc('year', v_timestamp)::date - interval'1 day'; end if; else raise exception 'U-2001 [%] is not recognize. please enter "D[1~366]"', p_formart; end if; elsif v_formart in ('HH', 'HH24') then v_timestamp := date_trunc('hour', p_timestamp); elsif v_formart = 'HH12' then v_timestamp := to_char(p_timestamp, 'yyyy-mm-dd hh12:00:00')::timestamp; elsif v_formart in ('MINUTE', 'MI') then v_timestamp := date_trunc('minute', p_timestamp); elsif v_formart = 'CC' then v_timestamp := to_date((trunc(date_part('years', p_timestamp)::integer/100)*100+1)::varchar, 'yyyy'); elsif v_formart in ('HELP', '?') then raise exception 'U-2001 please enter formart code in ( YYYY|YEAR, MONTH|MON|MM|RM, DD|DAY|DY, D, W[1~7], D[1~366], HH|HH24, HH12, MINUTE|MI, CC )'; else raise exception 'U-2001 [%] is not recognize. you can try [help]', p_formart; end if; else v_timestamp := p_timestamp; end if; return v_timestamp; end; $BODY$ LANGUAGE plpgsql VOLATILE COST 100
|