Home [SQL] Stored Procedure 預存程序的參數
Post
Cancel

[SQL] Stored Procedure 預存程序的參數

預存程序的參數有:

  1. Input 輸入參數
  2. Output 輸出參數
1
2
3
4
5
6
7
8
create proc uspGetCount
    --定義參數
    @id int = 1, --輸入參數
    @count int output --輸出參數(要加output)
as
begin
    --處理內容(SQL語句)
end

1. Input 輸入參數

Input 輸入參數:預設值以=來指定值,例如:@id = 1

呼叫預存程序的時候沒有指定引數值,就會以預設值處理

執行預存程序的方法

1
2
3
4
5
6
7
8
--無參數
exec stored_porcedure

--以位置名稱(必須按照SP變數定義的順序)
exec stored_porcedure value1, value2,...

--以參數名稱(可以不用按照順序)
exec stored_porcedure @param1 = value1, @param2 = value2,...
  • 按位置順序較簡單;按參數名稱可避免預存程序的參數因變換順序產生的錯誤。
  • 按位置順序的叫用,預存程序中含預設值的參數必須放在最後面;按參數名稱就沒這個限制。
  • 沒有預設值的參數都必須要傳入。

2. Output 輸出參數

Output 輸出參數:參數後面要加上 output
例如:@count output。(output可以簡寫為out)

執行預存程序,輸出引數也要加上output

建立預存程序時,參數後面必須使用 OUTPUT 關鍵字

1
2
3
4
5
6
7
8
9
10
11
12
--建立sp
create proc uspGetCount
    --定義參數
    @id int = 1, --輸入參數
    @count int output --輸出參數(要加output)
as
begin
    --處理內容(SQL語句)
    select @count = sum(數量) 
    from 販賣資料 
    where 商品ID = @id
end

執行預存程序時,參數值後面也必須使用 OUTPUT 關鍵字

1
2
3
4
--執行sp
declare @c int --宣告變數
exec uspGetCount 10, @c output --執行sp (輸出參數要加上output)
select @c --顯示結果

OUTPUT 參數是用來回傳一個值給應用程式時使用

範例(帶預設值的參數)

製作統計所指定商品ID的販賣數量的預存程序
取得的結果要儲存到參數中
當未傳入商品ID時,預設商品ID=1來處理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
--製作統計所指定商品ID的販賣數量的預存程序
--取得的結果要儲存到參數中
--當未傳入商品ID時,預設商品ID=1來處理
create proc uspGetCount
    --定義參數
    @id int = 1, --輸入參數
    @count int output --輸出參數(要加output)
as
begin
    --處理內容(SQL語句)
    select @count = sum(數量) 
    from 販賣資料 
    where 商品ID = @id
end

執行預存程序

傳入ID

1
2
3
declare @c int --宣告變數
exec uspGetCount 10, @c output --執行sp (輸出參數要加上output)
select @c --顯示結果

沒有傳入ID

沒有傳入商品ID,就會使用預設值(會在 @id = 1的情況下運作)。

1
2
3
declare @c int --宣告變數
exec uspGetCount @count = @c output --執行sp (省略引數@id,輸出參數要加上output)
select @c --顯示結果

引數 vs. 參數

  • 引數(Argument) 是用於呼叫函式。
  • 參數(Parameter) 是方法簽章(方法的宣告)。

MSDN - 執行預存程序
[SQL] Stored Procedure 預存程序的建立與刪除 [SQL] Stored Procedure 預存程序的建立
vito-note - Stored Procedures

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