使用return關鍵字進行返回
遇到return關鍵字存儲過程中的后續代碼無條件不執行,既退出了當前的存儲過程
根據返回值對存儲過程的結果做出相應的處理
例子:
1 --創建帶返回值的存儲過程 2 3 /* 4 向母嬰用品中添加一條商品信息 5 6 */ 7 use E_Market 8 go 9 if exists(select * from sysobjects where name='usp_InsertCommodityReturn') 10 drop proc usp_InsertCommodityReturn 11 12 go 13 create proc usp_InsertCommodityReturn 14 @SortName varchar(50), --類別名稱 15 @CommodityName varchar(100), --商品名稱 16 @inprice money, --進貨價 17 @outprice money, --銷售價 18 @Amount int --庫存liang 19 20 as 21 declare @sortid int 22 select @sortid=SortId from CommoditySort where SortName=@SortName 23 --根據類別名稱判斷類別編號是否存在 24 if @sortid is null 25 begin 26 return -1 --用-1代表類別名稱不正確 27 end 28 --向商品信息表添加一條信息 29 insert into CommodityInfo(SortId,CommodityName,InPrice,OutPrice,Amount) 30 values(@SortId,@CommodityName,@inprice,@outprice,@Amount) 31 if @@ERROR > 0 32 begin 33 return 0 --用0代表插入信息失敗 34 end 35 else 36 begin 37 return @@identity 38 end 39 go 40 41 --使用帶返回值的存儲過程,返回值,有三個,0,-1.商品編號 42 --使用顯示調用 43 declare @Result int --接收存儲過程的返回值 44 exec @Result=usp_InsertCommodityReturn @sortName='匯吃美食',@commodityName='好吃點',@inprice=3.5,@outprice=7.6,@amount=100 45 if @Result=-1 46 begin 47 print '對不起,輸入的類別名稱不存在!' 48 end 49 else if @Result=0 50 begin 51 print'插入信息失敗!' 52 end 53 else 54 begin 55 print '添加商品成功!商品編號為:' + convert(varchar(5),@Result) 56 end 57 go 58 59 select * from CommoditySort 60 select * from CommodityInfo