PostgreSQL9.5(Windows10 64bit環境)を使用しています。
PostgreSQLのwith句を使用したストアドプロシージャを作成し、実行しました。
内容は以下のようなものです。
CREATE TABLE public.point
(
_id serial,
_date date,
_value integer
)
_id | _date | _value |
---|---|---|
1 | '2018-05-01' | 1 |
2 | '2018-05-02' | 2 |
3 | '2018-05-03' | 3 |
SQL
1CREATE OR REPLACE FUNCTION public._sample_proc( 2 IN _target_date date 3) 4 RETURNS void AS 5$BODY$ 6DECLARE 7--変数宣言 8 _now_val integer; 9 _count integer; 10 _arr_id integer[]; 11BEGIN 12 13with 14x as ( 15select 16 point._id 17 ,point._date 18 ,SUM(point._value) over (order by _date) AS _sum_value 19 from point 20 where _value > 0 21 order by _date 22) 23 24 select count(*)+1 into _count from x where _sum_value < 2; 25 select array_agg(x._id) into _arr_id from x ; 26 27RETURN ; 28 29END; 30$BODY$ 31 LANGUAGE plpgsql VOLATILE 32 COST 100; 33ALTER FUNCTION public._sample_proc(date) 34 OWNER TO postgres;
上記を実行すると、
SQL
1select * from _sample_proc('2018-05-10'::date); 2 3ERROR: リレーション"x"は存在しません 4LINE 1: select array_agg(x._id) from x 5 ^ 6QUERY: select array_agg(x._id) from x 7CONTEXT: PL/pgSQL関数_sample_proc(date)の21行目の型SQL ステートメント 8 9********** エラー ********** 10 11ERROR: リレーション"x"は存在しません 12SQLステート:42P01 13コンテキスト:PL/pgSQL関数_sample_proc(date)の21行目の型SQL ステートメント
と出力されます。
withで定義したxを使用する2つのselectのうち、先に使用しているselectを無効にすると、
実行時のエラーは発生しません。
-- select count(*)+1 into _count from x where _sum_value < 2; select array_agg(x._id) into _arr_id from x ;
ストアドでwithを使用するのが不適切なのかもしれませんが、私のwithに対する認識は、
withで定義した問合せ結果を一時的に保持してくれるもの、
という認識です。動作的には、1つ目のselectで一時的な保存が無くなってしまうように見えるのですが
ストアドプロシージャ内で有効にし続ける方法はあるでしょうか。
よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/05/21 02:26