WHILE loops

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 loops

  • WHILE ประเมินเงื่อนไขว่าเป็นจริงหรือเท็จ

  • หลัง WHILE ต้องมีบรรทัดที่ใช้คีย์เวิร์ด BEGIN

  • จากนั้นใส่โค้ดที่จะรันจนกว่าเงื่อนไขใน WHILE loop จะเป็นจริง

  • หลังโค้ดให้ใส่คีย์เวิร์ด END

  • BREAK จะทำให้ออกจาก loop

  • CONTINUE จะทำให้ loop ทำงานต่อ

SQL Server ระดับกลาง

WHILE loop ใน T-SQL (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 ระดับกลาง

WHILE loop ใน T-SQL (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...