我正在尝试学习如何以及何时提交/回滚事务。
我正在使用IF
条件来测试代码是否产生错误,如果是,我想要回滚。
测试代码的最佳方法是什么,以便您知道何时提交或回滚。
我已经尝试过下面的代码但是我得到了这个错误
Msg 102,Level 15,State 1,Line 5 '*'附近的语法不正确。
Begin Transaction DBChallenge1Setup
Create Table EmployeeRecords(
EmployeeID varchar(50) PRIMARY KEY
PpsNo varchar(8),
FirstName varchar(50),
LastName varchar(50),
Department varchar(50),
SupervisorId varchar(50),
PhoneNo varchar(50),
EmailAddress varchar(50),
DateOfBirth date);
Insert Into EmployeeRecords
Values(1, '5686213Q', 'Dan', 'Roche', 'IT',232, '012323232', 'danroche@itsolutions.com', '1970-04-10'),
(2, '6534223Q', 'Nicholas', 'Martin', 'IT',233, '012323233', 'nicholasmartin@itsolutions.com', '1974-12-01'),
(232, '9514223W', 'Jane', 'Donnelly', 'IT',999, '012323234', 'janedonnelly@itsolutions.com', '1960-02-12'),
(233, '4212223S', 'Amy', 'Smythe', 'IT',999, '012323235', 'amysmythe@itsolutions.com', '1967-09-11');
Select * From EmployeeRecords
Select @@Rowcount As RecordsEntered, @@ERROR As Errors
if @@Error > 0 ROLLBACK Transaction DBChallenge1Setup
if @@Error = 0 Commit Transaction DBChallenge1Setup;
答案 0 :(得分:0)
我建议使用try/catch
来处理意外错误;
begin try
Begin Transaction DBChallenge1Setup
Create Table EmployeeRecords(
EmployeeID varchar(50,) PRIMARY KEY
PpsNo varchar(8),
FirstName varchar(50),
LastName varchar(50),
Department varchar(50),
SupervisorId varchar(50),
PhoneNo varchar(50),
EmailAddress varchar(50),
DateOfBirth date)
Insert Into EmployeeRecords
Values(1, '5686213Q', 'Dan', 'Roche', 'IT',232, '012323232', 'danroche@itsolutions.com', '1970-04-10'),
(2, '6534223Q', 'Nicholas', 'Martin', 'IT',233, '012323233', 'nicholasmartin@itsolutions.com', '1974-12-01'),
(232, '9514223W', 'Jane', 'Donnelly', 'IT',999, '012323234', 'janedonnelly@itsolutions.com', '1960-02-12'),
(233, '4212223S', 'Amy', 'Smythe', 'IT',999, '012323235', 'amysmythe@itsolutions.com', '1967-09-11');
Commit Transaction DBChallenge1Setup;
end try
begin catch
ROLLBACK Transaction DBChallenge1Setup
end catch
您应该在catch块中回滚事务。此外,最好使用ERROR_MESSAGE()
ERROR_SEVERITY()
等在catch块中记录发生的错误详细信息。