问题
I have a requirement to loop through a table having all the reporting periods right from 2010. I need to loop through this table so that i when I pass the date string, it takes at and compares it if it is less than the reporting_periods_o and returns back the reporting_period_string.
CREATE OR REPLACE FUNCTION rpt.reportingperiods(IN v_date text)
RETURNS SETOF text AS
$BODY$
DECLARE
v_in_date INT := CAST(v_date AS INT);
i INT;
v_sk INT;
BEGIN
For i IN SELECT rpt_sk FROM rpt.REPORTING_PERIODS LOOP
SELECT rpt_sk INTO v_sk FROM rpt.REPORTING_PERIODS where rpt_sk = i;
IF v_in_date <= (SELECT reporting_periods_o FROM rpt.REPORTING_PERIODS
WHERE rpt_sk = i)
THEN RETURN QUERY SELECT MIN(reporting_periods)reporting_periods FROM rpt.REPORTING_PERIODS WHERE rpt_sk = v_sk AND CAST(reporting_periods AS DATE) > CAST(now() AS DATE);
END IF;
END LOOP;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
ROWS 1000;
My reporting periods has three fields:
rpt_sk, reporting_periods, reporting_periods_o 1 2014-03-08 20140308
I have implemented a function but when I execute I am getting multiple records, I need to be able to get back one record.
来源:https://stackoverflow.com/questions/23301082/looping-through-a-postgres-table-and-returning-the-wekid