这篇文章主要介绍了postgres 使用存储过程批量插入数据的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
参考官方文档
create or replace function creatData2() returns
boolean AS
$BODY$
declare ii integer;
begin
II:=1;
FOR ii IN 1..10000000 LOOP
INSERT INTO ipm_model_history_data (res_model, res_id) VALUES (116, ii);
end loop;
return true;
end;
$BODY$
LANGUAGE plpgsql;
select * from creatData2() as tab;
插入1千万条数据耗时610s,当然字段不多的情况下。
补充:Postgresql存储过程--更新或者插入数据
要记录某一时段机器CPU、内存、硬盘的信息,展示的时间粒度为分钟,但是为了精确,输入数据源的时间粒度为6s。这个统计过程可以在应用层做好,每分钟插入一次,也可以在数据库层写个存储过程来完成,根据传入数据的时间来判断是更新数据库旧数据还是插入新数据。
同时,这些数据只需要保留一周,更老的数据需要被删除。删除动作可以每天定时执行一次,也可以写在存储过程中每次检查一下。
考虑到性能在此时没什么太大约束,而后面存储过程的接口方式更漂亮些,不用应用层去关心数据到底组织成什么样,因此实现了一个如下:
Postgresql V8.3
CREATE OR REPLACE FUNCTION insert_host_status(_log_date timestamp without time zone, _host inet, _cpu integer, _mem integer, _disk integer)
RETURNS void AS
$BODY$
DECLARE
new_start timestamp without time zone;
current_start timestamp without time zone;
c_id integer;
c_log_date timestamp without time zone;
c_cpu integer;
c_mem integer;
c_disk integer;
c_count integer;
date_span interval;
BEGIN
-- insert or update
SELECT id, log_date, cpu, mem, disk, count INTO c_id, c_log_date, c_cpu, c_mem, c_disk, c_count FROM host_status_byminute WHERE host=_host ORDER BY id DESC limit 1;
SELECT timestamp_mi(_log_date, c_log_date) INTO date_span;
IF date_span >= '00:00:60' OR c_id IS NULL THEN
INSERT INTO host_status_byminute (log_date, host, cpu, mem, disk, count) values (_log_date, _host, _cpu, _mem, _disk, 1);
ELSIF date_span >= '-00:00:60' THEN
c_mem := ((c_mem * c_count) + _mem)/(c_count + 1);
c_cpu := ((c_cpu * c_count) + _cpu)/(c_count + 1);
c_disk := ((c_disk * c_count) + _disk)/(c_count + 1);
c_count := c_count + 1;
UPDATE host_status_byminute SET mem=c_mem, cpu=c_cpu, disk=c_disk, count=c_count WHERE id=c_id;
END IF;
-- delete old data
SELECT date_mii(date(now()), 6) INTO new_start;
SELECT date(log_date) from host_status_byminute limit 1 INTO current_start; -- omit a bug happened when date is disordered.
IF new_start > current_start THEN
DELETE FROM host_status_byminute where log_date < new_start;
END IF;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE
COST 100;
ALTER FUNCTION insert_host_status(timestamp without time zone, inet, integer, integer, integer) OWNER TO dbuser_test;
文章来源:脚本之家
来源地址:https://www.jb51.net/article/205221.htm
免责声明:本平台仅供信息发布交流之途,请谨慎判断信息真伪。如遇虚假诈骗信息,请立即举报
举报