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?

【SQL】SQLって変数使えるんかい...

0
Last updated at Posted at 2026-03-23

今回は完全にメモです。

SQLって変数使えるらしい

簡単なSQLしか触ってこなかったから、今更知ったという恥ずかしさもありつつ...

変数に値をセット

以下のように記述することで、変数に値をセットすることができるようです。

-- SET に `@` をつけて任意の変数名
SET @sample_id = '~~~~~~'

変数の値を参照

INSERT文などで、@sample_idをそのまま記述することで変数展開がされます。

SET @name = 'サンプルデータ1'

-- VALUES('id','name','created_at','updated_at')
INSERT INTO samples VALUES(null,@name,current_timestamp,current_timestamp);

直前にINSERTしたレコードのIDを取得して展開する

-- INSERT
INSERT INTO samples VALUES(null,'サンプルデータ1',current_timestamp,current_timestamp);

-- 上でINSERTしたレコードのIDを取得
SET @sample_id = LAST_INSERT_ID();

-- 上でINSERTしたレコードの子レコードをINSERT
-- テーブル構成は VALUES('id','sample_id','name','created_at','updated_at') と仮定
INSERT INTO sample_items VALUES(null,@pattern_id,'サンプルデータ子要素1',current_timestamp,current_timestamp);
INSERT INTO sample_items VALUES(null,@pattern_id,'サンプルデータ子要素2',current_timestamp,current_timestamp);
INSERT INTO sample_items VALUES(null,@pattern_id,'サンプルデータ子要素3',current_timestamp,current_timestamp);

以上、メモでした。

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?