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

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

在預存程序中使用變數時,必須要先宣告。
Declare後宣告變數,變數名稱要以「@」為開頭,以Set來給變數賦值。

1
2
3
4
5
6
7
8
create procedure uspTest
    --定義參數
as
declare
    --宣告變數
begin
    --處理內容
end

範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
create or alter proc uspTest
    --定義參數
    @name varchar(20) output
as
declare
    --宣告變數
    @id int
begin
    --設定變數(賦值)
    set @id = 1
    --處理內容(SQL語句)
    select @name = 客戶名稱 
    from 客戶清單 
    where 客戶ID = @id
end

執行sp:

1
2
3
declare @name varchar(20) --宣告變數
exec uspTest @name output --執行sp
select @name as 'Customer' --顯示內容

執行結果:

1
2
Customer
Waikiki軟體

MSDN - SET @local_variable (Transact-SQL)
[SQL] 變數

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