LoginSignup
32
29

More than 1 year has passed since last update.

postgresでinsert時にデフォルトで登録された値をreturningで取得する

Last updated at Posted at 2013-07-11

postgresでinsert時にデフォルトで登録された値をreturningで取得する

  • Aテーブルにレコードをinsert
  • BテーブルにもAテーブルに紐づくレコードをinsertしたい
  • Aテーブルにinsertした際にシーケンスで登録されたIDを取得して使用したい!
-- データを INSERT
INSERT INTO hoge (hoge_id, hoge_text) VALUES (nextval('hoge_id_seq'), 'てすと');

-- 直前のシーケンス値を取得
SELECT currval('hoge_id_seq');

currvalが一般的だよな〜と思いながら、他にもなんかやり方あったよな〜
とおぼろげな記憶で探してたらあったあった

returning

INSERT INTO hoge (hoge_id, hoge_text) VALUES (nextval('hoge_id_seq'), 'てすと')
  RETURNING hoge_id;
  • RETURNINGリストの構文はSELECTの出力リストと同一です。 とのことで、SELECT文と同じように結果を取得してやれば、IDが取得できる!
32
29
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
32
29