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

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


如题:



SQL 利用存储过程实现对表数据有则更新无则添加_第1张图片 


表结构和基础数据如图所示:

新建存储过程:insertOrUpdate

  /*建立存储过程*/
  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

数据库中便会根据相应的操作进行更新或者插入,并返回值0或1


你可能感兴趣的:(SQL,Server)