您的位置:首页 > 数据库

Sql Server2008如何在存储过程中实现根据判断插入更新数据

2013-02-27 22:12 686 查看
原文链接:http://blog.csdn.net/liguiping2000/article/details/6878568

存储过程的功能非常强大,在某种程度上甚至可以替代业务逻辑层,接下来就一个小例子来说明,用存储过程插入或更新语句。

1、数据库表结构

所用数据库为Sql Server2008。

2、创建存储过程

(1)实现功能:

有相同的数据,直接返回(返回值:0);

有主键相同,但是数据不同的数据,进行更新处理(返回值:2);

没有数据,进行插入数据处理(返回值:1)。

根据不同的情况设置存储过程的返回值,调用存储过程的时候,根据不同的返回值,进行相关的处理。

(2)下面编码只是实现的基本的功能,具体的Sql代码如下:



[sql] view
plaincopy

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环境中简单的实现了调用,在程序中调用也很方便。

具体的代码如下:

[sql] view
plaincopy

declare @rtn int

exec sp_Insert_Student '1101','张三','男',23,@rtn output



if @rtn=0

print '已经存在相同的。'

else if @rtn=1

print '插入成功。'

else

print '更新成功'

一个存储过程就实现了3中情况,而且效率很高,使用灵活。 希望对大家有所帮助。

在成长学习的过程中,我会不断发一些自己的心得体会,和大家共享。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: