SQL Server編程(03)自定義存儲過程


存儲過程是一組預編譯的SQL語句,它可以包含數據操縱語句、變量、邏輯控制語句等。

存儲過程允許帶參數:

  • 輸入參數:可以在調用時向存儲過程傳遞參數,此類參數可用來向存儲過程中傳入值(可以有默認值)
  • 輸出參數:從存儲過程中返回(輸出)值,后面跟隨OUTPUT關鍵字

存儲過程的優點:

  1. 執行速度快
  2. 允許模塊化設計
  3. 提高系統安全性
  4. 減少網絡流量

創建存儲過程

我們可以使用create procedure命令創建存儲過程。

create procedure calcAge (
    @birthday datetime,    --輸入參數
    @age int output        --輸出參數,參數后面加 output
)
as
begin    --begin...end 語句塊不是必須的(即使是多條語句)
    declare @now datetime
    set @now=getdate()
    set @age=YEAR(@now)-YEAR(@birthday)    --為輸出參數賦值,不需要return
end

輸入參數帶默認值:

create procedure calcAge (
    @birthday datetime = '2012-1-1',    --輸入參數,帶默認值,調用的時候可以不指定
    @age int output        --輸出參數,參數后面加 output
)
as
begin    --begin...end 語句塊不是必須的(即使是多條語句)
    declare @now datetime
    set @now=getdate()
    set @age=YEAR(@now)-YEAR(@birthday)    --為輸出參數賦值,不需要return
end

 

調用存儲過程

我們新定義的存儲過程有輸出參數,調用的時候也需要指定參數為output

declare @age int
execute calcAge '2012-1-1', @age output        --標記參數@age為output
print @age

調用存儲過程時,默認情況下指定的參數是按照定義的數序指定的,我們也可以顯示的指定:

declare @myAge int
execute calcAge @age=@myAge output        --顯示指定參數@age
print @myAge

 

修改存儲過程

使用alter procedure命令修改存儲過程,例如下面的偽代碼:

alter procedure calcAge (
    @birthday datetime,
    @age int output
)
as
begin
    -- 這里是你的邏輯
end

 

刪除存儲過程

使用drop procedure命令刪除存儲過程:

drop procedure calcAge

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM