2013-05-26 128 views
2

我需要在查詢失敗時回滾事務。如果所有事務都正常,則必須設置輸出參數。提交事務失敗時設置輸出參數

到目前爲止,我已經做到了這一點。

create PROCEDURE [dbo].[sp_InsertAll] 
-- Add the parameters for the stored procedure here 
@WO_Type varchar(25), 
@WO_Operation varchar(25), 
@WO_Source varchar(25), 
@RETVAL BIT OUT 
AS 
BEGIN 
    SET NOCOUNT ON; 

    SET @RETVAL = 0 
    SET XACT_ABORT ON 

    BEGIN TRAN; 

     INSERT INTO tblTabl1(WO_Type , WO_Operation , WO_Source) 
     VALUES (@WO_Type, @WO_Operation, @WO_Source,) 

     IF @UPDATESOURCE = 1 
     BEGIN 
      UPDATE tblT2 
      SET SM_SaddleStatus = @SOURCESTATUS 
      WHERE SM_SaddleID = @WO_SourceID 
     END 

     IF @UPDATEDESTINATION = 1 
     BEGIN 
      UPDATE tblT3 
      SET SM_SaddleStatus = @DESTINATIONSTATUS 
      WHERE SM_SaddleID = @WO_DestinationID 
     END 

     SET @RETVAL = 1 
     COMMIT TRAN; 
END 

這是返回值的正確方法嗎?這個方法有什麼問題嗎?到目前爲止,它對我來說工作得很好。在轉入生產之前,我需要進行覈對。

回答

2

這就是我建議,使用TSQL try catch塊來回滾事務,給你一個不同的返回值:

create PROCEDURE [dbo].[sp_InsertAll] 
-- Add the parameters for the stored procedure here 
@WO_Type varchar(25), 
@WO_Operation varchar(25), 
@WO_Source varchar(25), 
[email protected] BIT OUT 
AS 

BEGIN 
SET NOCOUNT ON; 

SET @RETVAL = 0 
SET XACT_ABORT ON 

BEGIN TRAN; 
    BEGIN TRY 
       INSERT INTO tblTabl1(WO_Type , WO_Operation , WO_Source) 
       VALUES (@WO_Type, @WO_Operation, @WO_Source,) 

       IF @UPDATESOURCE = 1 
       BEGIN 
        UPDATE tblT2 
        SET SM_SaddleStatus = @SOURCESTATUS 
        WHERE SM_SaddleID = @WO_SourceID 
       END 

       IF @UPDATEDESTINATION = 1 
       BEGIN 
        UPDATE tblT3 
        SET SM_SaddleStatus = @DESTINATIONSTATUS 
        WHERE SM_SaddleID = @WO_DestinationID 
       END 

      return 0 
      COMMIT TRAN; 
    END TRY 
    BEGIN CATCH 
      rollback Tran; 
      return -1 
    END CATCH 
END 
+0

這是給「事務計數後EXECUTE指示的數量不匹配BEGIN和COMMIT?'錯誤..我在COMMIT TRAN語句旁邊移動了'return 0'statemnt。現在可以了。 – Olivarsham

相關問題