欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用postgresql的游标批量生成数据

程序员文章站 2024-02-10 14:09:10
...

 需求是给日志表里插入数据,数据是一年前的每隔五分钟生成一条记录。这里有个问题是,这条数据的id和创建时间都是不同的,所以可以使用generate_series() 函数来得到每隔五分钟的时间,然后将查询到的数据返回给游标,开始循环遍历游标,v_id作为每条记录的id号,并且递增。

CREATE OR REPLACE FUNCTION cursor_demo()
RETURNS refcursor AS
$BODY$
declare
unbound_refcursor cursor for select generate_series(to_date('20180307','yyyymmdd'), to_date('20180324','yyyymmdd'), '5 m');
v_id int;
v_createtime timestamp;
	begin
	v_id := 121589;
	open unbound_refcursor ;
	loop
	fetch unbound_refcursor into v_createtime;
		if found then
		INSERT INTO tbl_system_log("id","user_id","username","url","request_method","host","content","operation","create_date","device_mac")  
        VALUES( v_id,13,'admin','/system/login','POST','192.168.0.103','登录成功','登录',v_createtime,'70:B3:D5:C1:25:D7') ;
		else
			exit;
		end if;
		v_id = v_id +1;
	end loop;
	close unbound_refcursor;
		raise notice 'the end of msg...';
	return unbound_refcursor;
	exception when others then
	    raise exception 'error--(%)',sqlerrm;
end;
$BODY$
LANGUAGE plpgsql;

然后执行查询语句就可以生成数据

select cursor_demo();

下面是简单的批量生成数据

CREATE OR REPLACE FUNCTION proc_user () RETURNS void AS $$
	
BEGIN
        FOR i IN 106001..107000 LOOP 
		
        INSERT INTO tbl_system_log("id","user_id","username","url","request_method","host","content","operation","create_date","device_mac")  
        VALUES (i,13,'admin','/system/login','POST','192.168.0.103','登录成功','登录',to_timestamp('2018-03-22 21:21:21.4','YYYY-MM-DD HH24:MI:SS.MS'),'70:B3:D5:C1:25:D7') ;
	
	END loop ;
 
END $$ 
LANGUAGE 'plpgsql';
 
 
 
SELECT proc_user ();