WHILEループ

中級 SQL Server

Ginger Grant

Instructor

T-SQLでの変数の使用

  • 値を設定するには変数が必要

    DECLARE @variablename data_type

    • @文字で始める必要がある
中級 SQL Server

T-SQLの変数データ型

  • VARCHAR(n): 可変長テキスト
  • INT: -2,147,483,647〜+2,147,483,647の整数
  • DECIMAL(p ,s) または NUMERIC(p ,s):
    • p: 小数点の左右を含む格納桁数の合計
    • s: 小数点以下に格納する桁数
中級 SQL Server

T-SQLでの変数の宣言

-- Declare Snack as a VARCHAR with length 10
DECLARE @Snack VARCHAR(10)
中級 SQL Server

変数への値の代入

-- Declare the variable
DECLARE @Snack VARCHAR(10)
-- Use SET a value to the variable
SET @Snack = 'Cookies'
-- Show the value
SELECT @Snack
+--------------------+ 
|(No column name)    | 
+--------------------+
|Cookies             |
+--------------------+
-- Declare the variable
DECLARE @Snack VARCHAR(10)
-- Use SELECT assign a value
SELECT @Snack = 'Candy'
-- Show the value
SELECT @Snack
+--------------------+ 
|(No column name)    | 
+--------------------+
|Candy               |
+--------------------+
中級 SQL Server

WHILEループ

  • WHILEは真偽条件を評価する

  • WHILEの後にBEGINキーワードを記述する

  • 条件が真になるまで実行するコードを記述する

  • コードの後にENDキーワードを追加する

  • BREAKはループを終了する

  • CONTINUEはループを継続する

中級 SQL Server

T-SQLのWHILEループ (I)

-- Declare ctr as an integer
DECLARE @ctr INT
-- Assign 1 to ctr
SET @ctr = 1

-- Specify the condition of the WHILE loop WHILE @ctr < 10
-- Begin the code to execute inside WHILE loop BEGIN -- Keep incrementing the value of @ctr SET @ctr = @ctr + 1 -- End WHILE loop END -- View the value after the loop SELECT @ctr
+--------------------+ 
|(No column name)    | 
+--------------------+
|10                  |
+--------------------+
中級 SQL Server

T-SQLのWHILEループ (II)

-- Declare ctr as an integer
DECLARE @ctr INT
-- Assign 1 to ctr
SET @ctr = 1
-- Specify the condition of the WHILE loop
WHILE @ctr < 10
    -- Begin the code to execute inside WHILE loop
    BEGIN
       -- Keep incrementing the value of @ctr
       SET @ctr = @ctr + 1
       -- Check if ctr is equal to 4
       IF @ctr = 4
           -- When ctr is equal to 4, the loop will break
           BREAK
       -- End WHILE loop
    END
中級 SQL Server

練習しましょう!

中級 SQL Server

Preparing Video For Download...