こちらのサンプルを改造しました。
ストアドプロシージャの使い方(PostgreSQL)
city というデータベースに、ユーザー scott でアクセスできるとします。
テスト用のテーブルの作成
create.sql
drop table in01;
create table in01 (id int primary key, operand1 int, operand2 int);
insert into in01 values (1,10,9);
insert into in01 values (2,20,8);
insert into in01 values (3,30,7);
insert into in01 values (4,40,6);
insert into in01 values (5,50,5);
drop table out01;
create table out01 (id int primary key, sum int, diff int);
実行
$ psql -U scott -d city < create.sql
DROP TABLE
CREATE TABLE
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
INSERT 0 1
DROP TABLE
CREATE TABLE
ストアドプロシージャの作成
sum_diff_proc.sql
drop procedure sum_diff_proc;
CREATE PROCEDURE sum_diff_proc(int) AS $$
DECLARE
ope1 int;
ope2 int;
BEGIN
SELECT operand1 INTO ope1 FROM in01 WHERE id = $1;
SELECT operand2 INTO ope2 FROM in01 WHERE id = $1;
INSERT INTO out01 VALUES ($1, ope1 + ope2, ope1 - ope2);
END;
$$
LANGUAGE plpgsql;
実行
$ psql -U scott -d city < sum_diff_proc.sql
DROP PROCEDURE
CREATE PROCEDURE
ストアードプロシージャの実行
exec01.sql
select * from operand;
call sum_diff_proc(1);
call sum_diff_proc(2);
call sum_diff_proc(3);
call sum_diff_proc(4);
call sum_diff_proc(5);
select * from answer;
実行
$ psql -U scott -d city < exec01.sql
id | operand1 | operand2
----+----------+----------
1 | 10 | 9
2 | 20 | 8
3 | 30 | 7
4 | 40 | 6
5 | 50 | 5
(5 行)
CALL
CALL
CALL
CALL
CALL
id | sum | diff
----+-----+------
1 | 19 | 1
2 | 28 | 12
3 | 37 | 23
4 | 46 | 34
5 | 55 | 45
(5 行)
確認したバージョン
PostgreSQL 14.5 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 12.1.1 20220730, 64-bit