当我执行此存储过程时,即使IF
语句正确,我也无法在IF
块中回滚。如果IF
语句是正确的,脚本仍然在最后运行,并且根本没有回滚。
消息:帐户ID已使用成功注册
Msg 3902,Level 16,State 1,Procedure PROC_DANGKY,Line 23
COMMIT TRANSACTION请求没有相应的BEGIN TRANSACTION。
代码:
CREATE PROCEDURE PROC_REGISTER
@name nvarchar(30),
@birth datetime,
@passport nvarchar(9),
@address nvarchar(50),
@phone nvarchar(11),
@email nvarchar(20),
@account nvarchar(30),
@password nvarchar(20)
AS
BEGIN TRAN
BEGIN TRY
IF (EXISTS(SELECT * FROM CUSTOMER WHERE ACCOUNT = @account))
BEGIN
PRINT N'The account id has already been used'
ROLLBACK TRAN
END
INSERT INTO KHACHHANG
VALUES (@name, @birth, @passport, @address, @phone, @email, @account, @password)
PRINT N'Successfully registered'
END TRY
BEGIN CATCH
DECLARE @ErrorMsg VARCHAR(2000)
SELECT @ErrorMsg = N'Error: ' + ERROR_MESSAGE()
RAISERROR(@ErrorMsg, 16,1)
ROLLBACK TRAN
RETURN
END CATCH
COMMIT TRAN
答案 0 :(得分:1)
重新设置了您的查询
存在后删除回滚
CREATE PROC PROC_REGISTER
@name nvarchar(30),
@birth datetime,
@passport nvarchar(9),
@address nvarchar(50),
@phone nvarchar(11),
@email nvarchar(20),
@account nvarchar(30),
@password nvarchar(20)
AS
BEGIN TRAN
BEGIN TRY
IF (EXISTS(SELECT * FROM CUSTOMER WHERE ACCOUNT = @account))
PRINT N'The account id has already used'
ELSE
BEGIN
INSERT INTO KHACHHANG VALUES (@name, @birth, @passport, @address, @phone, @email, @account, @password)
PRINT N'Successul register'
END
END TRY
BEGIN CATCH
DECLARE @ErrorMsg VARCHAR(2000)
SELECT @ErrorMsg = N'Error: ' + ERROR_MESSAGE()
RAISERROR(@ErrorMsg, 16,1)
IF @@TRANCOUNT > 0
ROLLBACK TRAN
END CATCH
IF @@TRANCOUNT > 0
COMMIT TRAN
GO
RETURN
答案 1 :(得分:0)
如果事务存在,您可以在回滚到ckeck之前检查@@TRANCOUNT:
CREATE PROC PROC_REGISTER
@name nvarchar(30),
@birth datetime,
@passport nvarchar(9),
@address nvarchar(50),
@phone nvarchar(11),
@email nvarchar(20),
@account nvarchar(30),
@password nvarchar(20)
AS
BEGIN TRAN
BEGIN TRY
IF (EXISTS(SELECT * FROM CUSTOMER WHERE ACCOUNT = @account))
BEGIN
PRINT N'The account id has already used'
IF (@@TRANCOUNT > 0)
BEGIN
ROLLBACK TRAN
END
END
INSERT INTO KHACHHANG VALUES (@name, @birth, @passport, @address, @phone, @email, @account, @password)
PRINT N'Successul register'
END TRY
BEGIN CATCH
DECLARE @ErrorMsg VARCHAR(2000)
SELECT @ErrorMsg = N'Error: ' + ERROR_MESSAGE()
RAISERROR(@ErrorMsg, 16,1)
IF (@@TRANCOUNT > 0)
BEGIN
ROLLBACK TRAN
END
RETURN
END CATCH
COMMIT TRAN