使用模式名称的变量创建“插入到”函数

时间:2012-03-14 17:11:17

标签: postgresql

我正在尝试创建一个将数据插入表格的函数。我正在使用的查询不会改变,除了模式名称需要是变量。例如,我的一个模式名称是bscu.members,然后还有另外35个非常相似(wea.members,pcu.members .. etc等...)。我找不到任何有关如何使用变量在Postgresql中创建函数的帮助。

这是我到目前为止所提出的,但它无法正常工作

create or replace function attsummary(varchar)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
 BEGIN
insert into dwh.attribution_summary
select
m.source,
m.name,
m.partner_id,
d.ucic,
b.acct_type_desc as acct_desc,
a.begin_mo_balance as opening_balance,
c.date,
h.campaignname,
g.description as banner_desc,
f.create_time::timestamp as time_served,
'd' as dep_or_loan,
'h' as home_or_nonhome  
   from
$1.fact_deposits a
join $1.dim_acct_type b on a.acct_type_id = b.acct_type_id
join $1.dim_date c on a.date_id = c.date_id
join $1.dim_members d on a.ucic = d.ucic
join ad_delivery.sgmt_adic e on d.adic::varchar = e.adic
join ad_delivery.sgmt_user_tracker f on e.cookie_id = f.id
join ad_delivery.ox_banners g on g.bannerid = f.banner_id
join ad_delivery.ox_campaigns h on h.campaignid = f.campaign_id
join ad_delivery.sgmt_kli_adic i on e.adic = i.adic
join dwh.sgmt_clients m on m.partner_id = i.sgmt_partner_id
   where
  i.kli=8616208
   and m.partner_id::integer != 909909

然后我的select语句出现..我使用$ 1作为模式名称通常的变量。

2 个答案:

答案 0 :(得分:3)

必须动态生成

create or replace function attsummary
(schema text)
returns void as
$body$
begin
execute format('
insert into dwh.attribution_summary
select
    m.source,
    m.name,
    m.partner_id,
    d.ucic,
    b.acct_type_desc as acct_desc,
    a.begin_mo_balance as opening_balance,
    c.date,
    h.campaignname,
    g.description as banner_desc,
    f.create_time::timestamp as time_served,
    ''d'' as dep_or_loan,
    ''h'' as home_or_nonhome  
from
%1$s.fact_deposits a
join %1$s.dim_acct_type b on a.acct_type_id = b.acct_type_id
join %1$s.dim_date c on a.date_id = c.date_id
join %1$s.dim_members d on a.ucic = d.ucic
join ad_delivery.sgmt_adic e on d.adic::varchar = e.adic
join ad_delivery.sgmt_user_tracker f on e.cookie_id = f.id
join ad_delivery.ox_banners g on g.bannerid = f.banner_id
join ad_delivery.ox_campaigns h on h.campaignid = f.campaign_id
join ad_delivery.sgmt_kli_adic i on e.adic = i.adic
join dwh.sgmt_clients m on m.partner_id = i.sgmt_partner_id
where
    i.kli=8616208
    and m.partner_id::integer != 909909
', $1);
end;
$body$
language plpgsql volatile
;

答案 1 :(得分:1)

@Clodoaldo给了你一个有效的答案,但请注意他使用的format()函数在Pg 9.1之前是不可用的。如果需要它来处理较旧的Pg实例,可以使用字符串表达式来构建动态查询。例如:

CREATE SCHEMA a;
CREATE SCHEMA b;

CREATE TABLE a.foo ( data text );
CREATE TABLE b.foo ( data text );

CREATE OR REPLACE FUNCTION insert_with_schema(schema_name text, data text)
  RETURNS void
AS  $$
BEGIN
  EXECUTE 'INSERT INTO ' || quote_ident(schema_name) || '.foo (data) VALUES ($1)'
    USING data;
END
$$
LANGUAGE plpgsql;