0

Suppose I have an array of state abbreviations like this:

states text[] := ARRAY['al', 'ak', 'az', 'ar', 'ca', 
'co', 'ct', 'de', 'dc', 'fl', 'ga', 'hi', 'id', 'il', 
'in', 'ia', 'ks', 'ky', 'la', 'me', 'md', 'ma', 'mi', 
'mn', 'ms', 'mo', 'mt', 'ne', 'nv', 'nh', 'nj', 'nm', 
'ny', 'nc', 'nd', 'oh', 'ok', 'or', 'pa', 'ri', 'sc', 
'sd', 'tn', 'tx', 'ut', 'vt', 'va', 'wa', 'wv', 'wi', 
'wy', 'pr', 'vi'];

I want to loop or iterate through this array list and plug the individual state abbreviations into a function as a parameter and run it. Note: I also have the same data in a table called states under the same schema with a column called st_abbr. Here's the function:

CREATE OR REPLACE FUNCTION pop_allocation_sql.st_fips_updater2(
    st_abbr text
 )
    RETURNS VOID   
  AS
$$
DECLARE 

BEGIN
 -- logic
 EXECUTE format(
    'UPDATE pop_allocation_output_12102021.%s_population_allocation_20210202
        SET st_fips = LEFT(geoid, 2)
        WHERE st_fips <> LEFT(geoid, 2)',
  st_abbr);
END;
$$ LANGUAGE plpgsql
VOLATILE; 

How would I do that?

1
  • "How would I do that?" -- The best you can do is to revise that schema and unite those several tables into one with columns for the country and day. Commented Jan 27, 2022 at 14:14

1 Answer 1

1

No need to use a loop, you can use unnest() to generate one row for each array element.

select pop_allocation_sql.st_fips_updater2(state)
from unnest(ARRAY['al', 'ak', 'az', 'ar', 'ca', 
                 'co', 'ct', 'de', 'dc', 'fl', 'ga', 'hi', 'id', 'il', 
                 'in', 'ia', 'ks', 'ky', 'la', 'me', 'md', 'ma', 'mi', 
                 'mn', 'ms', 'mo', 'mt', 'ne', 'nv', 'nh', 'nj', 'nm', 
                 'ny', 'nc', 'nd', 'oh', 'ok', 'or', 'pa', 'ri', 'sc', 
                 'sd', 'tn', 'tx', 'ut', 'vt', 'va', 'wa', 'wv', 'wi', 
                 'wy', 'pr', 'vi']) as t(state);

If those abbreviations are available in a different table, there is no need to use an array or a variable:

select pop_allocation_sql.st_fips_updater2(st_abbr)
from states

But your data model seems rather strange. You shouldn't have one table for each state, but a single table where state is a column.

Sign up to request clarification or add additional context in comments.

1 Comment

I went with your second suggestion using the table and worked like a charm. I feel like I wasted time trying to iterate through an array when I already had the data in a table. BTW - this function is a 'clean-up' for existing tables. But I took your single table comment to heart from another answer you gave and redid my new workflow to be single national tables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.