我正在实施一个执行UPDATE
,DELETE
和INSERT
的关键任务存储过程,我想确保我的TRANSACTION
正确形成。
我已经看过一些TRANSACTION
语句,每个步骤后都会检查一下。我也看到过这种情况,整个步骤都放在一个TRANSACTION
块内,没有任何"检查点"一路上。
这是一个格式良好的TRANSACTION
,如果在任何时候出现任何错误,它会回滚所有内容,即UPDATE
,DELETE
和INSERT
。< / p>
这里是TRANSACTION
:
BEGIN TRANSACTION
BEGIN TRY
UPDATE SomeTable
SET SomeColumnValue = 123
WHERE Id = 123456
DELETE FROM SomeOtherTable
WHERE Id = 789
INSERT INTO ThirdTable
(Column1, Column2)
VALUE
('Hello World', 1234567)
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
END CATCH
答案 0 :(得分:3)
您可以使用以下语法。请注意,当从begin try块内部调用另一个具有类似结构的SP时,语法也会处理嵌套事务
BEGIN TRAN
BEGIN TRY
UPDATE SomeTable
SET SomeColumnValue = 123
WHERE Id = 123456
DELETE FROM SomeOtherTable
WHERE Id = 789
INSERT INTO ThirdTable
(Column1, Column2)
VALUE
('Hello World', 1234567)
COMMIT TRAN
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN;
INSERT INTO LogError (
--ErrorID
objectName
,ErrorCode
,ErrorDescription
,ErrorGenerationTime
)
SELECT
-- autogenerated
OBJECT_NAME(@@PROCID)
,ERROR_NUMBER() AS ErrorCode
,'Error of Severity: ' + CAST (ERROR_SEVERITY() AS VARCHAR (4))
+' and State: ' + CAST (ERROR_STATE() AS VARCHAR (8))
+' occured in Line: ' + CAST (ERROR_LINE() AS VARCHAR (10))
+' with following Message: ' + ERROR_MESSAGE() AS ErrorColumnDescription
,GETDATE()
END CATCH
答案 1 :(得分:2)
您需要在try块中调用 COMMIT TRANSACTION 。这将是try块中的最后一个语句。因此,如果一切顺利,那么它将被提交,否则它将在catch块中回滚。