【SQL】ストアド ~ 基本編 / 繰り返し ~

■ はじめに

ストアドのループについて扱う

目次

【0】ドキュメント
【1】FOR文
【2】WHILE文
【3】BREAK文
【4】CONTINUE文

【0】ドキュメント

PostgreSQL
https://www.postgresql.jp/document/7.2/programmer/plpgsql-control-structures.html

【1】FOR文

例1

  FOR i IN 1..10 LOOP
    IF i < 3 THEN
      INSERT INTO demo_result VALUES (i, 'Hello');
    ELSEIF i < 7 THEN
      INSERT INTO demo_result VALUES (i, 'World');
    ELSE
      INSERT INTO demo_result VALUES (i, 'Others');
    END IF;
  END LOOP;

例2

FOR value IN (SELECT v FROM demo_table)
LOOP
  -- 繰り返し処理
END LOOP;

【2】WHILE文

1)サンプル

DECLARE @counter int;
SET @counter = 0;

WHILE (@counter < 100)
BEGIN
  /* 繰り返したい処理 */
  SET @counter = @counter + 1;
END

【3】BREAK文

1)サンプル

DECLARE @counter int;
SET @counter = 0;

WHILE (@counter < 100)
BEGIN
  /* 繰り返したい処理 */

  IF @counter = 10
    BREAK;
  ELSE
    SET @counter = @counter + 1;
END

【4】CONTINUE文

1)サンプル

DECLARE @counter int;
SET @counter = 0;

WHILE (@counter < 100)
BEGIN
  /* 繰り返したい処理 */

  IF @counter = 10
    CONTINUE;
  ELSE
    SET @counter = @counter + 1;
END

参考文献

http://www.near-future.com/sqlserver/03_1.html

関連記事

ストアド ~ 基礎知識編 ~
https://dk521123.hatenablog.com/entry/2010/08/06/112528
ストアド ~ 基本編 / 変数 ~
https://dk521123.hatenablog.com/entry/2013/01/25/002936
ストアド ~ 基本編 / 条件分岐 ~
https://dk521123.hatenablog.com/entry/2024/11/12/005529
PostgreSQL】ストアド ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2014/04/21/000100
PostgreSQL】ストアド ~ SELECT INTO ~
https://dk521123.hatenablog.com/entry/2024/11/11/212756