SQL 利用存储过程实现对表数据有则更新无则添加(转)

       初学存储过程,发现这篇文章简单易懂,特意转载,地址

       http://blog.csdn.net/luotuomianyang/article/details/52013144

       如果某一操作包含大量的T-SQL语句代码,分别被多次执行,那么存储过程要比批处理的执行速度快得多。因为存储过程是预编译的,在首次运行一个存储过程时,查询优化器对其进行分析、优化,并给出最终被存在系统表中的存储计划。而批处理的T-SQL语句每次运行都需要预编译和优化,所以速度就要慢一些。

如题:

 

 

  

 

/*建立存储过程*/  
create procedure insertOrUpdate  
@BookName varchar (50),  
@Price float,  
@Publish varchar (50),  
@id int,  
@Storage int,  
@returnValue int output  
as  
  
/*判断该id号的书是否已经存在*/  
if exists (select * from Book where id=@id)    
begin  
/*更新数据*/  
update Book set BookName=@BookName ,Price=@Price where id=@id  
/*设置返回值*/  
set @returnValue=0  
end   
  
else   
begin   
/*插入*/  
insert into Book values(@BookName,@Price,@Publish,@id,@Storage)  
set @returnValue=1  
end  

 

执行操作:

 

declare @returnValue int  
exec insertOrUpdate '123',99.0,'真贵出版社',13,3,@returnValue output  
select @returnValue  

结果显示:

posted on 2018-01-15 13:56  鲁广广  阅读(512)  评论(0)    收藏  举报

导航