我正在尝试编写一个循环遍历表的 plpgsql 函数。在每个循环中,它从表中提取一行,将其存储在一条记录中,然后在查询的连接子句中使用该记录。这是我的代码:
CREATE OR REPLACE FUNCTION "testfncjh2" () RETURNS int
IMMUTABLE
SECURITY DEFINER
AS $dbvis$
DECLARE
counter int;
tablesize int;
rec1 record;
tablename text;
rec2 record;
BEGIN
counter = 0;
for rec1 in SELECT * FROM poilocations_sridconv loop
raise notice 'here';
execute $$ select count(*) from $$||rec1||$$ $$ into tablesize;
while counter < tablesize loop
counter = counter + 1;
raise notice 'hi';
execute $$ select count(*) from cities_sridconv $$ into tablesize;
end loop;
end loop;
return counter;
END;
$dbvis$ LANGUAGE plpgsql;
每次我运行它时,我都会收到以下错误:
错误:找不到数据类型记录的数组类型
有没有办法在嵌套循环内的查询中将该行用作表?
我的最终目标是构建一个循环遍历表的函数,在每个循环中从该表中提取一行。在每个循环中,使用行计算一个数字 COUNTER,然后根据行和 COUNTER 执行查询。知道此代码目前存在很大缺陷,因此我将其发布在下面以了解我正在尝试做什么:
创建或替换函数 "testfncjh" () 返回 void IMMUTABLE SECURITY DEFINER AS $dbvis$ DECLARE counter int; 表格大小 int; rec1 记录;表名文本;rec2 记录;开始
for rec1 in SELECT * FROM poilocations_sridconv loop
counter = 0;
execute $$ select count(*)
from $$||rec1||$$ a
join
cities_srid_conv b
on right(a.geom_wgs_pois,$$||counter||$$) = right(b.geom_wgs_pois,$$||counter||$$) $$ into tablesize;
raise notice 'got through first execute';
while tablesize = 0 loop
counter = counter + 1;
execute $$ select count(*)
from '||rec1||' a
join
cities_srid_conv b
on right(a.geom_wgs_pois,'||counter||') = right(b.geom_wgs_pois,'||counter||') $$ into tablesize;
raise notice 'hi';
end loop;
EXECUTE
'select
poiname,
name as cityname,
postgis.ST_Distance(postgis.ST_GeomFromText(''POINT(poilat poilong)''),
postgis.ST_GeomFromText(''POINT(citylat citylong)'')
) as distance
from (select a.poiname,
a.latitude::text as poilat,
a.longitude::text as poilong,
b.geonameid,
b.name,
b.latitude as citylat,
b.longitude as citylong
from '||rec1||' a
join cities_srid_conv b
on right(a.geom_wgs_pois,'||counter||') = right(b.geom_wgs_pois,'||counter||'))
) x
order by distance
limit 1'
poi_cities_match (poiname, cityname, distance); ------SQL STATEMENT TO INSERT CLOSEST CITY TO TABLE POI_CITIES_MATCH
end loop;
END;
$dbvis$ LANGUAGE plpgsql;
我在 PostgreSQL 8.2.15 数据库上运行。
另外,很抱歉重新发布。我不得不从原始数据中删除一些数据。