随机函数
--function to get random number=============================================================
-- DROP FUNCTION IF EXISTS get_random_number(integer, integer);
CREATE OR REPLACE FUNCTION get_random_number(integer, integer) RETURNS integer AS
$BODY$
DECLARE
start_int ALIAS FOR $1;
end_int ALIAS FOR $2;
BEGIN
RETURN trunc(random() * (end_int-start_int + 1) + start_int);
END;
$BODY$
LANGUAGE plpgsql;
--产生1-10之间的随机数(包括边缘)
--SELECT get_random_number(1, 10);
--function for get random date between start_date and end_date
-- DROP FUNCTION IF EXISTS get_random_date(date, date);
CREATE OR REPLACE FUNCTION get_random_date(start_date date, end_date date) RETURNS integer AS
$BODY$
DECLARE
interval_days integer;
random_days integer;
random_date date;
BEGIN
interval_days := end_date - start_date;
random_days := get_random_number(0, interval_days);
random_date := start_date + random_days;
RETURN date_part('year', random_date) * 10000 + date_part('month', random_date) * 100 + date_part('day', random_date);
END;
$BODY$
LANGUAGE plpgsql;
-- SELECT get_random_date('2000-01-01', '2013-12-31');--result:201009