Reputation: 12304
What is the problem with this code.
It is giving this error The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.
when some exception is coming in the procedure. How can I solve it?
BEGIN
BEGIN TRANSACTION
DECLARE
@Id bigint
,@Month nvarchar(100)
,@Year nvarchar(100)
,@CountryofExport nvarchar(100)
,@CountryofOrigin nvarchar(100)
,@HSCode nvarchar(100)
,@Unit nvarchar(100)
,@Quantity nvarchar(100)
,@CustomValue nvarchar(255)
,@Type nvarchar(100)
,@TypeBit bit
,@CountryofExportID int
,@CountryofOriginID int
,@MeasurementId int
,@Remarks nvarchar(500)
,@CommodityId int
,@SDate nvarchar(100)
,@SameRec int
,@counts int
DECLARE @Cursor_TradeFlow CURSOR
SET @Cursor_TradeFlow = CURSOR FOR
SELECT [Id],[Months],[Years],[CountryofExport],[CountryofOrigin],[HSCode],[Quantity],[Unit],[CustomValue],[Type] FROM [Temp_Trading]
OPEN @Cursor_TradeFlow
FETCH NEXT FROM @Cursor_TradeFlow INTO @Id, @Month, @Year, @CountryofExport, @CountryofOrigin, @HSCode,@Quantity, @Unit, @CustomValue, @Type
WHILE @@FETCH_STATUS = 0
BEGIN
Set @Remarks='';
Declare @EICountry varchar(100),
@Checkbit bit,
@CheckYearIsNumeric bit,
@CheckMonthIsNumeric bit
BEGIN TRY
SET @CheckMonthIsNumeric= convert(INT, @Month);
END TRY
BEGIN CATCH
begin
set @Checkbit=1;
set @Remarks = @Remarks + 'Invalid Month'
set @CheckMonthIsNumeric=1
end
END CATCH
BEGIN TRY
set @CheckYearIsNumeric= convert(INT, @Year);
END TRY
BEGIN CATCH
SET @CheckYearIsNumeric= 1;
set @Checkbit=1;
set @Remarks = @Remarks + 'Invalid Year'
END CATCH
Set @SameRec = (Select COUNT(*) From TradeFlow Where int_Month = @CheckMonthIsNumeric and int_Year = @CheckYearIsNumeric
and int_OriginLocationId = @CountryofExportID and int_DestinationLocationId = @CountryofOriginID and int_CommodityId = @CommodityId
and int_MeasurementId = @MeasurementId)
IF @@ERROR <> 0
BEGIN
ROLLBACK
END
FETCH NEXT FROM @Cursor_TradeFlow INTO @Id, @Month, @Year, @CountryofExport, @CountryofOrigin, @HSCode,@Quantity, @Unit, @CustomValue, @Type
END
CLOSE @Cursor_TradeFlow
DEALLOCATE @Cursor_TradeFlow
COMMIT
END
Upvotes: 1
Views: 9871
Reputation: 8695
You could use named transactions:
-- big transaction in the beginning
BEGIN TRANSACTION BIG_TRANSACTION-- your code here -- a transaction for each fetched item BEGIN TRANSACTION FETCH_TRANSACTION -- your code here if OK COMMIT TRANSACTION FETCH_TRANSACTION else ROLLBACK TRANSACTION FETCH_TRANSACTION
COMMIT/ROLLBACK TRANSACTION BIG_TRANSACTION
Upvotes: 0
Reputation: 239824
Having:
IF @@ERROR <> 0
BEGIN
ROLLBACK
END
inside a cursor loop is a bad sign - you rollback the transaction, and then continue into the next iteration. When the loop finally finishes, you attempt to commit and - Oops - there's no open transaction any longer, and every operation after the rollback has been left in place.
You might want to exit the loop after the rollback using a GOTO
, or deal with the errors in a different way. It's too hard to tell what the best strategy might be.
Upvotes: 7