我正在嘗試編寫一個循環遍歷表的plpgsql函數。在每個循環中,它從表中拉出一行,將其存儲在記錄中,然後在查詢的連接子句中使用該記錄。這裏是我的代碼:在函數中使用行作爲查詢中的表格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;
每次我跑,我得到了以下錯誤:
ERROR: could not find array type for data type record
是否有使用行作爲表查詢嵌套循環內的方法嗎?
我的最終目標是建立一個循環遍歷表的函數,在每個循環中從該表拉出一行。在每個循環中,使用該行計算COUNTER個數,然後根據行和COUNTER執行查詢。知道了這個代碼是目前非常有缺陷的,我下面張貼給的什麼,我試圖做一個想法:
CREATE OR REPLACE FUNCTION「testfncjh」()返回void IMMUTABLE SECURITY DEFINER AS $ dbvis $ DECLARE counter int; tablesize int; rec1記錄; tablename text; rec2記錄; BEGIN
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數據庫上運行。
此外,很抱歉轉貼。我不得不從原始數據中刪除一些數據。