我想把一张大桌子分成几张小桌子。我有以下代码片段,可以通过手动将"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$

最佳答案

循环变量应该只是text。在循环中使用simpleFOREACH循环(不使用SLICE)和动态SQLEXECUTE

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$

请参阅文档:
Looping Through Arrays
Executing Dynamic Commands
format

10-08 03:09