每当任何一个查询失败时,我都需要回滚事务。如果所有事务都没有问题,则必须设置输出参数。
到目前为止,我已经这样做了。
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
这是返回价值的正确方法吗?这个方法有什么问题吗?到目前为止它对我来说很好。在开始生产之前,我需要交叉检查。
答案 0 :(得分:3)
这就是我的建议,使用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),
--@RETVAL 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