GOTO (Transact-SQL)

將執行流程變更到標籤。略過一或多個遵照 GOTO 的 Transact-SQL 陳述式,從標籤開始繼續處理。程序、批次或陳述式區塊內的任何位置,都可以使用 GOTO 陳述式。GOTO 陳述式可以有巢狀結構。

主題連結圖示Transact-SQL 語法慣例

語法

Define the label: 
label : 
Alter the execution:
GOTO label 

引數

  • label
    這是 GOTO 的目標標籤,處理程序在這個點之後開始。標籤必須遵照識別碼的規則。標籤可用來作為是使用 GOTO 的註解化方法。

備註

GOTO 可以在條件式流程控制陳述式、陳述式區塊或程序內,但它不能移至批次之外的標籤。GOTO 分支可以移至定義在 GOTO 之前或之後的標籤。

權限

GOTO 權限預設會授與任何有效的使用者。

範例

下列範例顯示如何使用 GOTO 做為分支機制。

DECLARE @Counter int;
SET @Counter = 1;
WHILE @Counter < 10
BEGIN 
    SELECT @Counter
    SET @Counter = @Counter + 1
    IF @Counter = 4 GOTO Branch_One --Jumps to the first branch.
    IF @Counter = 5 GOTO Branch_Two  --This will never execute.
END
Branch_One:
    SELECT 'Jumping To Branch One.'
    GOTO Branch_Three; --This will prevent Branch_Two from executing.
Branch_Two:
    SELECT 'Jumping To Branch Two.'
Branch_Three:
    SELECT 'Jumping To Branch Three.'