1. 程式人生 > 資料庫 >SQLServer2008儲存過程實現資料插入與更新

SQLServer2008儲存過程實現資料插入與更新

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

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

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

3、呼叫儲存過程

這裡在Sql Server環境中簡單的實現了呼叫,在程式中呼叫也很方便。

具體的程式碼如下:

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

一個儲存過程就實現了3中情況,而且效率很高,使用靈活。 希望對大家有所幫助。