欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【ERROR】EXECUTE 后的事务计数指示 BEGIN 和 COMMIT 语句的数目不匹配。上一计数 = 0,当前计数 = 1。

程序员文章站 2024-02-20 15:46:10
...

【ERROR】EXECUTE 后的事务计数指示 BEGIN 和 COMMIT 语句的数目不匹配。上一计数 = 0,当前计数 = 1。

/*建立新表SC_Avg,记录任意一门课的平均成绩*/
DROP TABLE IF EXISTS SC_Avg;
CREATE TABLE SC_Avg
(
Cno CHAR(4),
Cname CHAR(10),
Avg_Score FLOAT 
)
INSERT INTO SC_Avg VALUES('1','高等数学',0)
INSERT INTO SC_Avg VALUES('2','计算机基础',0)
INSERT INTO SC_Avg VALUES('3','离散数学',0)
SELECT * FROM SC_Avg
/*建立存储过程*/
IF(exists(select * from sys.objects where name='Proc_TRANSFER1'))
	DROP PROCEDURE Proc_TRANSFER1
GO
CREATE PROCEDURE Proc_TRANSFER1
AS
BEGIN TRANSACTION TRANS
	DECLARE /*定义变量*/
	@Avg1 FLOAT,
	@Avg2 FLOAT,
	@Avg3 FLOAT;
	
	SELECT @Avg1=AVG(Grade)
	FROM SC
	WHERE Cno ='1'
	UPDATE SC_Avg SET Avg_Score=@Avg1 WHERE Cno ='1'

	SELECT @Avg2=AVG(Grade)
	FROM SC
	WHERE Cno ='2'
	UPDATE SC_Avg SET Avg_Score=@Avg2 WHERE Cno ='2'

	SELECT @Avg3=AVG(Grade)
	FROM SC
	WHERE Cno ='3'
	UPDATE SC_Avg SET Avg_Score=@Avg3 WHERE Cno ='3'
	

EXEC Proc_TRANSFER1

SELECT * FROM SC_Avg

原因在于BEGIN和COMMIT的语句数目不匹配
这时候,需要加上一句

COMMIT TRANSACTION TRANS

使程序修改为

/*建立新表SC_Avg,记录任意一门课的平均成绩*/
DROP TABLE IF EXISTS SC_Avg;
CREATE TABLE SC_Avg
(
Cno CHAR(4),
Cname CHAR(10),
Avg_Score FLOAT 
)
INSERT INTO SC_Avg VALUES('1','高等数学',0)
INSERT INTO SC_Avg VALUES('2','计算机基础',0)
INSERT INTO SC_Avg VALUES('3','离散数学',0)
SELECT * FROM SC_Avg
/*建立存储过程*/
IF(exists(select * from sys.objects where name='Proc_TRANSFER1'))
	DROP PROCEDURE Proc_TRANSFER1
GO
CREATE PROCEDURE Proc_TRANSFER1
AS
BEGIN TRANSACTION TRANS
	DECLARE /*定义变量*/
	@Avg1 FLOAT,
	@Avg2 FLOAT,
	@Avg3 FLOAT;
	
	SELECT @Avg1=AVG(Grade)
	FROM SC
	WHERE Cno ='1'
	UPDATE SC_Avg SET Avg_Score=@Avg1 WHERE Cno ='1'

	SELECT @Avg2=AVG(Grade)
	FROM SC
	WHERE Cno ='2'
	UPDATE SC_Avg SET Avg_Score=@Avg2 WHERE Cno ='2'

	SELECT @Avg3=AVG(Grade)
	FROM SC
	WHERE Cno ='3'
	UPDATE SC_Avg SET Avg_Score=@Avg3 WHERE Cno ='3'
	COMMIT TRANSACTION TRANS

EXEC Proc_TRANSFER1

SELECT * FROM SC_Avg