错误" EXECUTE后的事务计数表示BEGIN和COMMIT语句的数量不匹配"

时间:2017-09-29 20:55:37

标签: sql-server tsql

我在尝试执行t-sql存储过程时遇到标题错误

EXEC Add500ToChecking 18568

我尝试删除return和go语句,但它没有工作

USE [JProCo]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROC [dbo].[Add500ToChecking] @CustID INT AS

BEGIN TRAN

UPDATE SavAccount SET Balance = Balance - 500
WHERE CustomerID = @CustID
IF ( (SELECT Balance FROM SavAccount WHERE CustomerID = @CustID) < 0)
ROLLBACK TRAN
RETURN

UPDATE CkAccount SET Balance = Balance + 500
WHERE CustomerID = @CustID

COMMIT TRAN
RETURN
GO

知道我的代码会发生什么变化吗?这是一个课程项目

1 个答案:

答案 0 :(得分:3)

您的BEGIN声明需要一对ENDIF

UPDATE SavAccount SET Balance = Balance - 500
WHERE CustomerID = @CustID
IF ( (SELECT Balance FROM SavAccount WHERE CustomerID = @CustID) < 0)
BEGIN
    ROLLBACK TRAN
    RETURN
END

如上所述,只有ROLLBACK TRANIF语句的一部分,因此如果IF检查失败,它不会回滚事务,而是立即执行{{1} }}