当前位置:Gxlcms > mssql > SQLServer存储过程中事务的使用方法

SQLServer存储过程中事务的使用方法

时间:2021-07-01 10:21:17 帮助过:160人阅读

本文为大家分享了SQLServer存储过程中事务的使用方法,具体代码如下

  1. create proc usp_Stock
  2. @GoodsId int,
  3. @Number int,
  4. @StockPrice money,
  5. @SupplierId int,
  6. @EmpId int,
  7. @StockUnit varchar(50),
  8. @StockDate datetime,
  9. @TotalMoney money ,
  10. @ActMoney money ,
  11. @baseId int,
  12. @Description nvarchar(255)
  13. as
  14. declare @error int =0 --事务中操作的错误记录
  15. --开启事务
  16. begin transaction
  17. --实现进货信息的添加
  18. insert into StockInfo values(@GoodsId, @Number, @StockPrice, @SupplierId, @EmpId, @StockUnit, @StockDate, @TotalMoney, @ActMoney,DEFAULT,@Description, @baseId)
  19. set @error+=@@ERROR --记录有可能产生的错误号
  20. --获取当前进货信息的标识列
  21. --判断当前商品有没有进货记录
  22. if exists (select * from dbo.InventoryInfo where goodid=@GoodsId) --说明记录存在,直接修改库存数量
  23. begin
  24. update dbo.InventoryInfo set GNumber=GNumber+@Number,TotalMoney+=@TotalMoney where goodid=@GoodsId
  25. set @error+=@@ERROR --记录有可能产生的错误号
  26. end
  27. else --这个商品从来没有过进货记录,那么就应该添加新的存在信息
  28. begin
  29. declare @GWarningNum int --此商品的预警数量
  30. --获取预警数量
  31. set @GWarningNum=(select WaringNum from dbo.GoodsInfo where GId=@GoodsId)
  32. insert into dbo.InventoryInfo values(@GoodsId,@Number,@baseId,@GWarningNum,@TotalMoney,'第一次进货',default)
  33. set @error+=@@ERROR --记录有可能产生的错误号
  34. end
  35. --判断事务的提交或者回滚
  36. if(@error<>0)
  37. begin
  38. rollback transaction
  39. return -1 --设置操作结果错误标识
  40. end
  41. else
  42. begin
  43. commit transaction
  44. return 1 --操作成功的标识
  45. end
  46. go

希望本文所述对大家学习数据库操作有所帮助。

您可能感兴趣的文章:

  • c#实现sqlserver事务处理示例
  • SQL Server触发器及触发器中的事务学习
  • sqlserver中的事务和锁详细解析
  • Sqlserver 存储过程中结合事务的代码
  • SQLSERVER分布式事务使用实例
  • 浅析SQL Server中包含事务的存储过程
  • sqlserver 函数、存储过程、游标与事务模板
  • SQL Server存储过程中编写事务处理的方法小结
  • Sql Server中的事务介绍
  • Sql Server事务语法及使用方法实例分析

人气教程排行