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$
Are you sure, you can actually use
TRUNCATE
? Quoting the manual for 8.2:TRUNCATE
cannot be used on a table that has foreign-key references from other tables, unless all such tables are also truncated in the same command.If tables are small,
DELETE
is faster thanTRUNCATE
to begin with:
DELETE FROM dwh.prod_table_notify;
You have to sanitize identifiers! Use
quote_ident()
, also available in pg 8.2.No point in using
DISTINCT
here.Provide a column definition list for your
INSERT
. Else it can break in confusing ways, when you change the table later.If rows in the two legs of the
SELECT
are unique, useUNION ALL
instead ofUNION
. No point in trying to fold duplicates.