使用循环将参数插入 PostgreSQL 中的函数

Using a loop to plug parameters into a function in PostgreSQL

假设我有一个这样的州缩写数组:

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'];

我想循环或遍历这个数组列表,并将各个州的缩写作为参数插入到一个函数中,然后 运行 它。注意:我在名为 states 的 table 中也有相同的数据,在同一模式下有一个名为 st_abbr 的列。这是函数:

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; 

我该怎么做?

无需使用循环,可以使用unnest()为每个数组元素生成一行。

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);

如果这些缩写在不同的 table 中可用,则无需使用数组或变量:

select pop_allocation_sql.st_fips_updater2(st_abbr)
from states

但是您的数据模型似乎很奇怪。每个州不应该有一个 table,而应该有一个 table,其中 state 是一列。