Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through a string array and create multiple tables in Postgresql

I would like to take a large table and break in up into smaller ones. I have the following code snippet which works by manually replacing "NAME" with the unique name in 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")

My question is how do I loop through a list of names and populate the above code? I have tried the following, but it doesn't work:

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$
like image 531
Jscore Avatar asked Sep 03 '26 05:09

Jscore


1 Answers

The loop variable should be just text. Use simple FOREACH loop (without SLICE) and dynamic SQL EXECUTE inside the loop:

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$

Read also in the documentation:

  • Looping Through Arrays
  • Executing Dynamic Commands
  • format.
like image 103
klin Avatar answered Sep 05 '26 06:09

klin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!