3 回答

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以將set xact_abort on
事務(wù)放在事務(wù)之前,以確保sql在發(fā)生錯(cuò)誤的情況下自動(dòng)回滾。

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
您是正確的,因?yàn)檎麄€(gè)事務(wù)都會(huì)回滾。您應(yīng)該發(fā)出命令以將其回滾。
您可以TRY CATCH按以下步驟將其包裝
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO myTable (myColumns ...) VALUES (myValues ...);
INSERT INTO myTable (myColumns ...) VALUES (myValues ...);
INSERT INTO myTable (myColumns ...) VALUES (myValues ...);
COMMIT TRAN -- Transaction Success!
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN --RollBack in case of Error
-- you can Raise ERROR with RAISEERROR() Statement including the details of the exception
RAISERROR(ERROR_MESSAGE(), ERROR_SEVERITY(), 1)
END CATCH

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超8個(gè)贊
這是獲取與錯(cuò)誤消息一起使用MSSQL Server 2016的代碼:
BEGIN TRY
BEGIN TRANSACTION
-- Do your stuff that might fail here
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN
DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE()
DECLARE @ErrorSeverity INT = ERROR_SEVERITY()
DECLARE @ErrorState INT = ERROR_STATE()
-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH
添加回答
舉報(bào)