存储过程与事务

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了存储过程与事务相关的知识,希望对你有一定的参考价值。

USE BOOK 
GO
--删除表
IF OBJECT_ID(‘tb_Money‘) IS NOT NULL
DROP TABLE tb_Money
GO
--创建表
CREATE TABLE tb_Money(
 Id INT IDENTITY(1,1) PRIMARY KEY,
 Name VARCHAR(50) NOT NULL,
 MyMoney DECIMAL NOT NULL
)
--插入数据
INSERT INTO dbo.tb_Money (  Name, MyMoney )VALUES  (‘刘备‘, 100 )
INSERT INTO dbo.tb_Money (  Name, MyMoney )VALUES  (‘关羽‘, 20 )


--事务开始
BEGIN TRAN Tran_Money
DECLARE @tran_error INT;
SET @tran_error = 0;
DECLARE @FromPeple VARCHAR(50);
DECLARE @ToPeple VARCHAR(50);
DECLARE @HowMoney DECIMAL;
SET @FromPeple = ‘关羽‘;
SET @ToPeple = ‘刘备‘;
SET @HowMoney = 30;
BEGIN TRY
IF (((SELECT MyMoney FROM dbo.tb_Money WHERE Name = @FromPeple) - @HowMoney) < 0)
  BEGIN
       PRINT ‘余额不足‘;
       SET @tran_error = @tran_error + 1;
  END
ELSE
  BEGIN
      UPDATE dbo.tb_Money SET MyMoney = MyMoney - 30 WHERE Name = @FromPeple ;
	  SET @tran_error = @tran_error + @@ERROR; 
	  UPDATE dbo.tb_Money SET MyMoney = MyMoney + 30 WHERE Name = @ToPeple ;
	  SET @tran_error = @tran_error + @@ERROR; 
  END
END TRY
BEGIN CATCH
  PRINT ‘出现异常,错误编号:‘ + CONVERT(VARCHAR,ERROR_NUMBER()) + ‘错误消息:‘ + ERROR_MESSAGE()
  SET @tran_error = @tran_error + 1
END CATCH
IF(@tran_error > 0)
BEGIN
   ROLLBACK TRAN;--
   PRINT ‘转账失败,取消交易‘
END
ELSE
BEGIN
  COMMIT TRAN;
  PRINT ‘转账成功‘
END



--转账存储过程
IF OBJECT_ID(‘Pro_TranMoney‘) IS NOT NULL
DROP PROCEDURE Pro_TranMoney 
GO 
CREATE PROCEDURE Pro_TranMoney
@FromPeple VARCHAR(50),
@ToPeple VARCHAR(50),
@HowMoney DECIMAL
AS
BEGIN
--存储过程中的事务
--事务开始
BEGIN TRAN Tran_Money
DECLARE @tran_error INT;
SET @tran_error = 0;
BEGIN TRY
IF (((SELECT MyMoney FROM dbo.tb_Money WHERE Name = @FromPeple) - @HowMoney) < 0)
  BEGIN
       PRINT ‘余额不足‘;
       SET @tran_error = @tran_error + 1;
  END
ELSE
  BEGIN
      UPDATE dbo.tb_Money SET MyMoney = MyMoney - 30 WHERE Name = @FromPeple ;
	  SET @tran_error = @tran_error + @@ERROR; 
	  UPDATE dbo.tb_Money SET MyMoney = MyMoney + 30 WHERE Name = @ToPeple ;
	  SET @tran_error = @tran_error + @@ERROR; 
  END
END TRY
BEGIN CATCH
  PRINT ‘出现异常,错误编号:‘ + CONVERT(VARCHAR,ERROR_NUMBER()) + ‘错误消息:‘ + ERROR_MESSAGE()
  SET @tran_error = @tran_error + 1
END CATCH
IF(@tran_error > 0)
BEGIN
   ROLLBACK TRAN;--
   PRINT ‘转账失败,取消交易‘
END
ELSE
BEGIN
  COMMIT TRAN;
  PRINT ‘转账成功‘
END
END

--测试转账存储过程
EXEC dbo.Pro_TranMoney @FromPeple = ‘刘备‘,@ToPeple = ‘关羽‘, @HowMoney = 30

  

以上是关于存储过程与事务的主要内容,如果未能解决你的问题,请参考以下文章

mysql存储过程之事务篇

mysql存储过程与事务

事务与存储过程

存储过程与事务

事务与存储过程以及两者的区别

SQL Server:如果从 .net 代码中取消,则存储过程中打开的事务的默认操作