如何遍历字符串数组并在Postgresql中创建多个表

时间:2018-06-25 11:41:36

标签: postgresql loops plpgsql declare

我想拿一张大桌子,分成几个小桌子。我有以下代码片段,可以通过用"NAME"中的唯一名称手动替换ui00000bvbb.lad15nm来工作:

   CREATE TABLE "NAME" AS
   SELECT parcels_all_shapefile.* AS parcels
   FROM ui00000bvbb INNER JOIN parcels_all_shapefile ON ST_Intersects(ui00000bvbb.wkb_geometry, parcels_all_shapefile.wkb_geometry)
   WHERE ui00000bvbb.lad15nm = "NAME")

我的问题是如何遍历名称列表并填充上面的代码?我已经尝试了以下方法,但是不起作用:

DO
$do$
DECLARE
   m   varchar[];
   arr varchar[] := array[['Barnet'],['Westminster']];
BEGIN
   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
       CREATE TABLE m AS
       SELECT parcels_all_shapefile.* AS parcels
       FROM ui00000bvbb INNER JOIN parcels_all_shapefile ON ST_Intersects(ui00000bvbb.wkb_geometry, parcels_all_shapefile.wkb_geometry)
       WHERE ui00000bvbb.lad15nm = m)
   END LOOP;
END
$do$

1 个答案:

答案 0 :(得分:1)

循环变量应仅为text。在循环内使用简单的FOREACH循环(不使用SLICE)和动态SQL EXECUTE

DO
$do$
DECLARE
    m   text;
    arr text[] := array['Barnet','Westminster'];
BEGIN
   FOREACH m IN ARRAY arr
   LOOP
        EXECUTE format($fmt$
            CREATE TABLE %1$I AS
            SELECT parcels_all_shapefile.* AS parcels
            FROM ui00000bvbb INNER JOIN parcels_all_shapefile ON ST_Intersects(ui00000bvbb.wkb_geometry, parcels_all_shapefile.wkb_geometry)
            WHERE ui00000bvbb.lad15nm = %1$L
        $fmt$, m);
   END LOOP;
END
$do$

另请参阅文档: