接下来就一个小例子来说明,用存储过程插入或更新语句。
1、数据库表结构
所用数据库为Sql Server2008。
Create
proc sp_Insert_Student
2 @Nochar(10),
3 @Namevarchar(20),
4 @Sexchar(2),
5 @Ageint,
6 @rtnint output
7 as
8 declare
9 @tmpNamevarchar(20),
10 @tmpSexchar(2),
11 @tmpAgeint
12
13 ifexists(select*
from Studentwhere No=@No)
14 begin
15 select@tmpName=Name,@tmpSex=Sex,@tmpAge=Agefrom
Studentwhere 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 Studentset Name=@Name,Sex=@Sex,Age=@Agewhere
No=@No
23
set
@rtn=2 --有主键相同的数据,进行更新处理
24
end
25 end
26 else
27 begin
28 insertinto Studentvalues(@No,@Name,@Sex,@Age)
29 set@rtn=1
--没有相同的数据,进行插入处理
30 end
2、创建存储过程
(1)实现功能:1)有相同的数据,直接返回(返回值:0);
2)有主键相同,但是数据不同的数据,进行更新处理(返回值:2);
3)没有数据,进行插入数据处理(返回值:1)。
根据不同的情况设置存储过程的返回值,调用存储过程的时候,根据不同的返回值,进行相关的处理。
(2)下面编码只是实现的基本的功能,具体的Sql代码如下:
3、调用存储过程
这里在Sql Server环境中简单的实现了调用,在程序中调用也很方便。
具体的代码如下: