特定のスキーマ名をループしてデータをテーブルに挿入する関数があります。挿入ループが発生する前に、上記のテーブルを切り捨てたいと思います。切り捨てステートメントを動的クエリ内に配置しようとしたところ、スキーマのデータのみがテーブル内に保持されました。また、それを独自の変数として宣言してから、ループステートメントとは別にステートメントを実行しようとしましたが、結果は同じでした。
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$