mysql stored procedures with return values

存儲過程的功能非常強大,在某種程度上甚至可以替代業務邏輯層,

接下來就一個小例子來說明,用存儲過程插入或更新語句。

1、數據庫表結構

    所用數據庫爲Sql Server2008。

2、創建存儲過程

(1)實現功能:1)有相同的數據,直接返回(返回值:0);

2)有主鍵相同,但是數據不同的數據,進行更新處理(返回值:2);

3)沒有數據,進行插入數據處理(返回值:1)。

    根據不同的情況設置存儲過程的返回值,調用存儲過程的時候,根據不同的返回值,進行相關的處理。

(2)下面編碼只是實現的基本的功能,具體的Sql代碼如下:

Create proc sp_Insert_Student
     @No char(10),
     @Name varchar(20),
     @Sex char(2),
     @Age int,
     @rtn int output
as
declare
     @tmpName varchar(20),
     @tmpSex char(2),
     @tmpAge int
     if exists(select * from Student where No=@No)
         begin
             select @tmpName=Name,@tmpSex=Sex,@tmpAge=Age from Student where No=@No
             if ((@tmpName=@Name) and (@tmpSex=@Sex) and (@tmpAge=@Age))
                 begin
                     set @rtn=0   --有相同的數據,直接返回值
                 end
             else
                 begin
                     update Student set Name=@Name,Sex=@Sex,Age=@Age where No=@No
                     set @rtn=2   --有主鍵相同的數據,進行更新處理
                 end
         end
     else
         begin
             insert into Student values(@No,@Name,@Sex,@Age)
             set @rtn=1    --沒有相同的數據,進行插入處理
         end

 

 

execute:

declare @rtn int
exec sp_Insert_Student '1101','張三','男',23,@rtn output
if @rtn=0
     print '已經存在相同的。'
else if @rtn=1
     print '插入成功。'
else
     print '更新成功'

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章