在之前的問題Problem with alter then update in try catch with tran using Transact-SQL中,我發現爲了讓SQL運行起來,我不得不將它分成兩批。這是SQL的:Transact-SQL - 如果第一批失敗,如何防止第二批運行?
USE PUK;
GO
BEGIN TRANSACTION;
BEGIN TRY
-- - Modify RETRIEVAL_STAT
alter table dbo.RETRIEVAL_STAT add
SOURCE nvarchar(10) NULL,
ACCOUNTNUMBER nvarchar(50) NULL,
PUK nvarchar(20) NULL;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO
USE PUK;
GO
BEGIN TRANSACTION;
BEGIN TRY
-- transform logic.
UPDATE dbo.RETRIEVAL_STAT
SET SOURCE = 'ABC',
ACCOUNTNUMBER = ABC.ACCOUNTNUMBER,
PUK = ABC.PUK
FROM RETRIEVAL_STAT RS
INNER JOIN ABC
ON RS.SERVICE_NUMBER = ABC.SERVICENUMBER;
--- ... snip
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO
我現在的問題是:如果第一批次失敗,如何防止第二批次運行?
感謝您的任何建議!
羅布 :)
可能重複[SQL服務器 - 停止或中斷一個SQL腳本的執行(http://stackoverflow.com/questions/659188/sql-server-stop-or-break-execution-of-a -sql-script) –
@Martin Smith好的** ** raiserror('哦,沒有致命的錯誤',20,-1)和log **很好地完成了這項工作。謝謝。 –
@Martin Smith再次想到,我仍然缺少一些信息:如何檢測錯誤情況?在上面的例子中,我試着改變alter table的名字,並把RAISERROR放入catch中。它沒有工作。它告訴我**無法找到對象「dbo.RETRIEVAL_SdTAT」,因爲它不存在或者您沒有權限。**並且愉快地繼續運行其餘的SQL。 –