Home [SQL] Begin End 區塊
Post
Cancel

[SQL] Begin End 區塊

BEGIN…END 語句簡介

BEGIN...END語句用來定義語句區塊,語句區塊由一組一起執行的SQL語句組成。
語句區塊也稱為「批次處理」。(可以定義一系列同時執行的 T-SQL 陳述句)
換句話說,如果語句是句子,則BEGIN...END語句允許定義段落。
(如果有多句陳述句要一起執行就應該使用BEGIN END 包起來)

語法

1
2
3
BEGIN
    { sql_statement | statement_block}
END

如果 Begin End 中間只有單行程式碼,Begin End可省略不打。

範例1

1
2
3
4
5
6
7
begin
    --查出id=100的商品
    select * from 商品清單 where 商品ID = 100
    --如果沒有商品,則印出一條訊息
    if @@ROWCOUNT = 0
        print 'No product'
end

範例2: 巢狀 Begin End

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
begin
    --宣告變數
    declare @name nvarchar(20)
    --查詢id=3的商品名稱
    select @name = 商品名稱 from 商品清單 where 商品ID = 3
    --印出訊息
    if @@ROWCOUNT <> 0
    begin
        print 'Product is ' + @name
    end
    else
    begin
        print 'No product found'
    end
end

-- 執行結果:
-- Product is 17吋螢幕

MSDN - BEGIN…END (Transact-SQL)
SQL Server Begin End语句

This post is licensed under CC BY 4.0 by the author.