存儲過程的功能非常強大,在某種程度上甚至可以替代業務邏輯層,
接下來就一個小例子來說明,用存儲過程插入或更新語句。
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中情況,而且效率很高,使用靈活。 希望對大家有所幫助。
您可能感興趣的文章:- SQL Server 批量插入數據的完美解決方案
- Python實現讀取SQLServer數據并插入到MongoDB數據庫的方法示例
- SQLServer中防止并發插入重復數據的方法詳解
- 詳解C#批量插入數據到Sqlserver中的四種方式
- SQL Server批量插入數據案例詳解