0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PostgreSQL: ストアドファンクションの使い方

Posted at

こちらのサンプルを改造しました。
PostgreSQLで関数を作って、使う[PL/pgSQL入門]

city というデータベースに、ユーザー scott でアクセスできるとします。

テスト用のテーブルの作成

olympic.sql
DROP TABLE IF EXISTS host_cities;

CREATE TABLE host_cities (
  id SERIAL,
  name VARCHAR(255) NOT NULL,
  year INT NOT NULL
);

INSERT INTO host_cities(name, year) VALUES
  ('東京', 1964),
  ('メキシコシティ', 1968),
  ('ミュンヘン', 1972),
  ('モントリオール', 1976),
  ('モスクワ', 1980),
  ('ロサンゼルス', 1984),
  ('ソウル', 1988),
  ('バルセロナ', 1992),
  ('アトランタ', 1996),
  ('シドニー', 2000);

実行

$ psql -U scott -d city < olympic.sql 
DROP TABLE
CREATE TABLE
INSERT 0 10

ストアドファンクションの作成

years_ago.sql
DROP FUNCTION IF EXISTS years_ago(INTEGER);

CREATE OR REPLACE FUNCTION years_ago(year INTEGER)
RETURNS INTEGER AS $$
  BEGIN
    RETURN (extract(year from current_date)::INTEGER - year);
  END;
$$ LANGUAGE plpgsql;

実行

$ psql -U scott -d city < years_ago.sql 
DROP FUNCTION
CREATE FUNCTION

ストアードファンクションの実行

list.sql
SELECT name, year, years_ago(year) FROM host_cities;

実行

$ psql -U scott -d city < list.sql 
      name      | year | years_ago 
----------------+------+-----------
 東京           | 1964 |        58
 メキシコシティ | 1968 |        54
 ミュンヘン     | 1972 |        50
 モントリオール | 1976 |        46
 モスクワ       | 1980 |        42
 ロサンゼルス   | 1984 |        38
 ソウル         | 1988 |        34
 バルセロナ     | 1992 |        30
 アトランタ     | 1996 |        26
 シドニー       | 2000 |        22
(10 行)

確認したバージョン

PostgreSQL 14.5 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 12.1.1 20220730, 64-bit
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?