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 中级

Passons à la pratique !

SQL Server 中级

Preparing Video For Download...