Share via


使用 GOTO

GOTO 陳述式會導致執行 Transact-SQL 批次時,跳到某個標籤。在 GOTO 陳述式與該標籤之間的任何陳述式,都不會被執行。定義標籤名稱的語法如下:

        label_name:
      

請儘量少用 GOTO 陳述式。過度使用 GOTO 陳述式,會導致難以瞭解 Transact-SQL 批次的邏輯。使用 GOTO 實作的邏輯,幾乎都可以改用其他的流程控制陳述式來實作。GOTO 最適合用來突破深度巢狀結構的流程控制陳述式。

做為 GOTO 目標的標籤,只是用來識別跳躍點的目標。該標籤不會執行任何動作,來將它後面的陳述式與它前面的陳述式區隔開。任何使用者在執行緊接該標籤之前的陳述式時,都會略過該標籤,接著執行該標籤之後的陳述式。所有程式都是這樣執行的,除非緊接該標籤之前的陳述式本身就是流程控制陳述式 (例如 RETURN)。

以下是 GOTO 的範例:

IF (SELECT SYSTEM_USER()) = 'payroll'
   GOTO calculate_salary
-- Other program code would appear here.
-- When the IF statement evaluates to TRUE, the statements
-- between the GOTO and the calculate_salary label are
-- ignored. When the IF statement evaluates to FALSE the
-- statements following the GOTO are executed.
calculate_salary:
   -- Statements to calculate a salary would appear after the label.

請參閱

參考