存儲過程的功能非常強大,在某種程度上甚至可以替代業務邏輯層,
接下來就一個小例子來說明,用存儲過程插入或更新語句。
1、數據庫表結構
所用數據庫爲Sql Server2008。
2、創建存儲過程
(1)實現功能:1)有相同的數據,直接返回(返回值:0);
2)有主鍵相同,但是數據不同的數據,進行更新處理(返回值:2);
3)沒有數據,進行插入數據處理(返回值:1)。
根據不同的情況設置存儲過程的返回值,調用存儲過程的時候,根據不同的返回值,進行相關的處理。
(2)下面編碼只是實現的基本的功能,具體的Sql代碼如下:
1 Create proc sp_Insert_Student 2 @No char(10), 3 @Name varchar(20), 4 @Sex char(2), 5 @Age int, 6 @rtn int output 7 as 8 declare 9 @tmpName varchar(20), 10 @tmpSex char(2), 11 @tmpAge int 12 13 if exists(select * from Student where No=@No) 14 begin 15 select @tmpName=Name,@tmpSex=Sex,@tmpAge=Age from Student where No=@No 16 if ((@tmpName=@Name) and (@tmpSex=@Sex) and (@tmpAge=@Age)) 17 begin 18 set @rtn=0 --有相同的數據,直接返回值 19 end 20 else 21 begin 22 update Student set Name=@Name,Sex=@Sex,Age=@Age where No=@No 23 set @rtn=2 --有主鍵相同的數據,進行更新處理 24 end 25 end 26 else 27 begin 28 insert into Student values(@No,@Name,@Sex,@Age) 29 set @rtn=1 --沒有相同的數據,進行插入處理 30 end
3、調用存儲過程
這裏在Sql Server環境中簡單的實現了調用,在程序中調用也很方便。
具體的代碼如下:
1 declare @rtn int 2 exec sp_Insert_Student '1101','張三','男',23,@rtn output 3 4 if @rtn=0 5 print '已經存在相同的。' 6 else if @rtn=1 7 print '插入成功。' 8 else 9 print '更新成功'
一個存儲過程就實現了3中情況,而且效率很高,使用靈活。 希望對大家有所幫助。
在成長學習的過程中,我會不斷髮一些自己的心得體會,和大家共享。