qileilove

blog已经转移至github,大家请访问 http://qaseven.github.io/

如何在存储过程中实现插入更新数据

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

  1、数据库表结构

  所用数据库为Sql Server2008。

  2、创建存储过程

  (1)实现功能:

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

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

  没有数据,进行插入数据处理(返回值: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. if @rtn=0 
  4.     print '已经存在相同的。' 
  5. else if @rtn=1 
  6.     print '插入成功。' 
  7. else 
  8.     print '更新成功'

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

  在成长学习的过程中,我会不断发一些自己的心得体会,和大家共享。

posted on 2012-03-14 09:18 顺其自然EVO 阅读(661) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 
<2012年3月>
26272829123
45678910
11121314151617
18192021222324
25262728293031
1234567

导航

统计

常用链接

留言簿(55)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜