我需要构造一个所有插入查询的字符串数组,并在游标上迭代动态值。
过程如下:
CREATE OR REPLACE FUNCTION get_data()
RETURNS void AS $$
DECLARE
interval_time INTEGER DEFAULT 0;
rec_old RECORD;
rec_new RECORD;
rec_start RECORD;
v_filename VARCHAR(50);
querystring TEXT[];
cursor_file CURSOR FOR
select distinct(filename) from mytable.tableA;
cursor_data CURSOR FOR
select * from mytable.tableA where filename = v_filename order by mindatetime, maxdatetime;
BEGIN
--open the file cursor
OPEN cursor_file;
LOOP
FETCH cursor_file into v_filename;
EXIT WHEN NOT FOUND;
-- Open the second cursor
OPEN cursor_data;
FETCH cursor_data INTO rec_old;
rec_start = rec_old;
LOOP
-- fetch each record
FETCH cursor_data INTO rec_new;
interval_time := extract(epoch from rec_new.mindatetime) * 1000 - extract(epoch from rec_old.maxdatetime) * 1000;
IF interval_time = 1 THEN
-- swap the new and old rec
querystring='{insert into mytable.tableA values ('rec_new.fileid,rec_new.systemuid,rec_new.filename,rec_new.mindatetime,rec_new.maxdatetime')}';
raise notice 'query is %', querystring;
rec_old = rec_new;
ELSE
-- insert new records to other table
RAISE NOTICE 'Values to insert: %, % ', rec_start.mindatetime, rec_old.maxdatetime;
END IF;
-- exit when no more row to fetch
EXIT WHEN NOT FOUND;
END LOOP;
-- Close the cursor
CLOSE cursor_data;
END LOOP;
CLOSE cursor_file;
END; $$
LANGUAGE plpgsql;
我需要像这样的字符串数组:
{insert into mytable.tableA values ('123','dummyfilenameA','2019-04-21 03:06:26.0','2019-04-28 03:06:26.0'),
insert into mytable.tableA values ('456','dummyfilenameB','2019-05-21 03:06:26.0','2019-05-28 03:06:26.0')}
,依此类推。该数组应使用记录数据来构造查询。 最后,我要执行此查询字符串。有没有办法做到这一点?在遍历游标时无法更新表,因为它会影响已经存在的数据。
答案 0 :(得分:0)
如果您使用array_append(anyarray,anyelement)函数向数组querystring中添加元素?
querystring:=array_append(querystring,'insert...');