1

我有一个函数可以遍历特定的模式名称并将数据插入表中。我希望能够在插入循环发生之前截断所述表。我尝试将 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$
4

1 回答 1

2
CREATE OR REPLACE FUNCTION dwh.dim_table_notification()
  RETURNS void LANGUAGE plpgsql AS
$func$
DECLARE
   myschema text;
BEGIN

-- truncate simply goes here:
TRUNCATE dwh.prod_table_notify;

FOR myschema IN
   SELECT quote_ident(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
   EXECUTE '
   INSERT INTO dwh.prod_table_notify
              (userid, acct_type_id, acct_type, acct_type_desc, loan_type)
   SELECT '''|| myschema ||''', loan_type_id, loan_type::varchar(10)
        , loan_type_desc::varchar(50), term_code, 1 AS loan_type
   FROM   '|| myschema || '.dim_loan_type
   WHERE  term_code IS NULL
   UNION ALL
   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';
END LOOP;
END
$func$
  • 你确定,你真的可以使用TRUNCATE吗?引用8.2 的手册

    TRUNCATE不能用于具有来自其他表的外键引用的表,除非所有此类表也在同一命令中被截断。

    如果表很小DELETE则比TRUNCATE开始时要快:
    DELETE FROM dwh.prod_table_notify;

  • 你必须清理标识符!使用quote_ident(),也可在 pg 8.2 中找到。

  • 在这里使用没有意义DISTINCT

  • 为您的INSERT. 否则,当您稍后更改表格时,它可能会以令人困惑的方式中断。

  • 如果 的两条腿中的行SELECT是唯一的,请使用UNION ALL代替UNION。尝试折叠重复项毫无意义。

于 2013-08-11T13:31:47.637 回答