S-JIS[2020-11-26] 変更履歴

PL/pgSQL insert

PostgreSQLPL/pgSQLのinsert文について。


概要

PL/pgSQLでinsert文を書けば、insertが実行できる。

insert into テーブル (カラム, …) values(値, …);

begin
  insert into hoge (h_id, h_name) values(4, 'hoge4');
end
begin
  insert into hoge values(5, 'hoge5');
end
declare
  h_id   int;
  h_name text;
begin
  h_id   := 6;
  h_name := 'hoge6';
  insert into hoge (h_id, h_name) values(h_id, h_name);  
end

↑テーブル名の直後の丸括弧(カラム名)は、変数名と被っていても、変数とは認識されない(値に置換されたりはしない)。


複合型の例

複合型(テーブルの行型)の変数からinsertしたい場合。

declare
  h hoge;
begin
  h.h_id   := 7;
  h.h_name := 'hoge7';
  insert into hoge values (h);
end

↓実行結果

ERROR:  column "h_id" is of type integer but expression is of type hoge
行 1: insert into hoge values (h)
                               ^
HINT:  You will need to rewrite or cast the expression.

declare
  h hoge;
begin
  h.h_id   := 7;
  h.h_name := 'hoge7';
  insert into hoge values h;
end

ERROR:  syntax error at or near "h"
行 9:   insert into hoge values h;
                                ^

以下のようにすれば実行できる。

declare
  h hoge;
begin
  h.h_id   := 7;
  h.h_name := 'hoge7';
  insert into hoge values(h.*);
end

あるいは

declare
  h hoge;
begin
  h.h_id   := 7;
  h.h_name := 'hoge7';
  insert into hoge select h.*;
end

PL/pgSQLへ戻る / PostgreSQLへ戻る / 技術メモへ戻る
メールの送信先:ひしだま