EXECUTE问题后的事务计数

时间:2015-09-17 07:13:24

标签: sql-server sql-server-2008-r2

我编写了一个类似以下代码行的程序

ALTER PROCEDURE [dbo].[CountrySave]
(
@CountryId uniqueidentifier,
@CountryName nvarchar(max)
)
AS 
begin tran
if exists (select * from Country where CountryID =@CountryId)
begin
update Country set 
CountryID = @CountryId,
CountryName =@CountryName
where CountryID = @CountryId
end
else
begin
insert INTO Country(CountryID, CountryName) values 
(NewID(),@CountryName)
end

抛出" EXECUTE后的事务计数表示BEGIN和COMMIT语句的数量不匹配。先前的计数= 0,当前计数= 1。

在MARS批处理中启动的事务在批处理结束时仍处于活动状态。该交易将被回滚。"执行时出错! 请帮忙......

3 个答案:

答案 0 :(得分:0)

添加COMMIT TRAN

ALTER PROCEDURE [dbo].[CountrySave]
    @CountryId uniqueidentifier,
    @CountryName nvarchar(max)
AS 
BEGIN
BEGIN TRY
    BEGIN TRAN

    if exists (select * from Country where CountryID =@CountryId)
    begin
         update Country
         set CountryID = @CountryId,
             CountryName =@CountryName
         where CountryID = @CountryId;
     end
     else
     begin
        insert INTO Country(CountryID, CountryName)
        values(NewID(),@CountryName)
    end

    COMMIT TRAN
END TRY
BEGIN CATCH
    /* Error occured log it */
    ROLLBACK
END CATCH
END

答案 1 :(得分:0)

错误信息非常清楚。当你打开(开始)一个交易时,你也需要在它的最后做一些事情。

所以要么COMMIT事务(如果事务中的一个语句失败),要么wdDoc.inlineShapes(1).ScaleHeight = (wdDoc.Tables(3).Cell(2,1).Height) 事务,以便实际实现你的语句所做的所有更改。

来自MSDN:

  

BEGIN TRANSACTION表示a引用的数据的点   连接在逻辑上和物理上是一致的。如果有错误   遇到,在BEGIN TRANSACTION之后进行的所有数据修改   可以回滚以将数据返回到此已知状态   一致性。每笔交易都持续到没有完成   发出错误和COMMIT TRANSACTION以进行修改a   数据库的永久部分,或遇到错误和所有   使用ROLLBACK TRANSACTION语句擦除修改。

更多信息:https://msdn.microsoft.com/en-us/library/ms188929.aspx

答案 2 :(得分:0)

你的问题是你开始一个交易,但你永远不会提交/做回滚。

为您的程序试试这个结构,过去对我很有用:

CREATE PROCEDURE [dbo].SomeProc
    (@Parameter INT)
AS
BEGIN
    --if you want to be to only active transaction then uncomment this:
    --IF @@TRANCOUNT > 0
    --BEGIN
    --  RAISERROR('Other Transactions are active at the moment - Please try again later',16,1)
    --END

    BEGIN TRANSACTION

    BEGIN TRY
        /*
            DO SOMETHING
        */

        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        --Custom Error could be raised here
        --RAISERROR('Something bad happened when doing something',16,1)

        ROLLBACK TRANSACTION
    END CATCH
END