私はPL/pgSQLを使い慣れていません。これは私にとっては試行錯誤のようなものです。空の関数を作成しようとしていますが、呼び出されたときに表が生成されます。ここで私はこれまで持っているものです。入力の最後にPL/pgSQL構文エラーが発生しました
create or replace function counties()
returns table(code varchar(16), county varchar(50), count int) as $$
DECLARE
new_version varchar(50) := concat('sometext', max(REGEXP_REPLACE(COALESCE(schema_name, '0'), '[^0-9]*' ,'0')::integer), 'sometext') from information_schema.schemata where schema_name like 'gcversa%';
old_version varchar(50) := concat('sometext', max(REGEXP_REPLACE(COALESCE(schema_name, '0'), '[^0-9]*' ,'0')::integer)-2, 'sometext') from information_schema.schemata where schema_name like 'gcversa%';
BEGIN RETURN QUERY
with cte_current as (select distinct a.code as code, b.countyname as county from old_version a, public.counties b
where st_intersects(a.geom,b.geom) = True group by a.code, b.countyname),
cte_new as (select distinct a.code as code, b.countyname as county from new_version a, public.counties b
where st_intersects(a.geom,b.geom) = True group by a.code, b.countyname),
cte_union as (select code, county from cte_current
union all
select code, county from cte_new)
select code,county, count(*) as count
from cte_union
group by code, county
Having count (*) <> 2;
END;
$$
LANGUAGE plpgsql;
私が宣言している2つの変数が参照し、2つのPostgreSQLのスキーマのを連結した後、私はその後、労働組合それらのために、CTEのにそれらの変数を挿入しようとしていますすべて一緒に。私が正しく実行機能を得たが、私はselect counties()
を呼び出すときに、私はこのエラーを取得:
ERROR: relation "old_version" does not exist
LINE 1: ...tinct a.code as code, b.countyname as county from old_versio...
だから、それは私が宣言された変数、任意の提案を拾っていませんか?
UPDATE 私は動的SQLとformat()関数を使用しました。ここでは、最終的な作業モデルがどのように見えるかです:あなたは、ここで動的SQLが必要になります
drop function counties();
create or replace function counties()
returns table(code varchar(16), county varchar(50), count bigint) as $$
DECLARE
new_version_number varchar(50) := concat('gcversa00', MAX("versionnumber")) from "gcdefault"."versionhistory";
old_version_number varchar(50) := concat('gcversa00', MAX("versionnumber"-2)) from "gcdefault"."versionhistory";
BEGIN RETURN QUERY EXECUTE
format(
'with cte_current as (select distinct a.code as code, b.countyname as county from %I.servicearea a, public.counties b
where st_intersects(a.geom,b.geom) = True group by a.code, b.countyname),
cte_new as (select distinct a.code as code, b.countyname as county from %I.servicearea a, public.counties b
where st_intersects(a.geom,b.geom) = True group by a.code, b.countyname),
cte_union as (select code, county from cte_current
union all
select code, county from cte_new)
select code,county, count(*) as count
from cte_union
group by code, county
Having count (*) <> 2', new_version_number, old_version_number
);
END;
$$
LANGUAGE plpgsql;
あなたがここに動的SQLが必要になります - あなたはにリレーション名を置くために変数を使用することはできませんSQL –