我有一个函数可以遍历特定的模式名称并将数据插入表中。我希望能够在插入循环发生之前截断所述表。我尝试将 truncate 语句放在动态查询中,这导致它只将模式的数据保留在表中。我还尝试将它声明为它自己的变量,然后将语句与循环语句分开执行——但结果相同。
所以我的问题是——我究竟应该truncate table dwh.prod_table_notify
在这个函数中的什么地方添加一个语句?这样每次我运行这个函数时,表都会被截断,然后插入会正确地循环遍历从FOR
语句返回的每个模式。
注意:我被迫使用 postgres 8.2
CREATE OR REPLACE FUNCTION dwh.dim_table_notification()
RETURNS void
LANGUAGE plpgsql
AS $function$
Declare
myschema varchar;
sql2 text;
Begin
for myschema in
select distinct table_schema
from information_schema.tables
where table_name in ('dim_loan_type', 'dim_acct_type')
and table_schema NOT LIKE 'pg_%'
and table_schema NOT IN ('information_schema', 'ad_delivery', 'dwh', 'users', 'wand', 'ttd')
order by table_schema
loop
sql2 ='insert into dwh.prod_table_notify
select '''|| myschema ||''' as userid, loan_type_id as acct_type_id, loan_type::varchar(10) as acct_type, loan_type_desc::varchar(50) as acct_type_desc, term_code, 1 as loan_type from '|| myschema || '.' ||'dim_loan_type where term_code is null
union
select '''|| myschema ||''' as userid, acct_type_id, acct_type::varchar(10), acct_type_desc::varchar(50), term_code, 0 as loan_type from '|| myschema || '.' ||'dim_acct_type where term_code is null';
execute sql2;
end loop;
END;
$function$