存储过程给出错误:BEGIN和COMMIT语句的数量不匹配。先前的计数= 0,当前计数= 1

时间:2013-04-16 14:29:10

标签: transactions

ALTER PROCEDURE [dbo].[InsertAgent]
    (
        @State nvarchar(50),
        @StateCode int,
        @City nvarchar(50),
        @CityCode int,
        @FirstName nvarchar(100),
        @LastName nvarchar(100),
        @ParentName nvarchar(100),
        @Relationship nvarchar(100),
        @RelationshipCode int,
        @DOB date,
        @Age int,
        @Address nvarchar(250),
        @District nvarchar(50),
        @PIN int,
        @PANCardNo nvarchar(12),
        @Mobile1 nvarchar(14),
        @Mobile2 nvarchar(14),
        @OtherDetail nvarchar(250),
        @AgentCode nvarchar(20),
        @LevelRank int,
        @Agency Bit,
        @SeniorAgentID int,
        @Count int OUTPUT
    )
AS
    BEGIN
    /* SET NOCOUNT ON */
    SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; 
    DECLARE @AGENT_CODE nvarchar(15)
    BEGIN TRY

    BEGIN TRANSACTION 
        DECLARE @NewAgentCount INT = (SELECT MAX(AgentCount) FROM dbo.tbl_Agent WITH (TABLOCKX))+1;

        select @AGENT_CODE = @CityCode + 'A' + (SELECT RIGHT('000000'+ CONVERT(VARCHAR,AgentCount),7) AS AgtCode FROM dbo.tbl_Agent);

            BEGIN
                    INSERT INTO tbl_Agent(State, StateCode, City, CityCode, FirstName,LastName,ParentName, Relationship, RelationshipCode, DOB,Age,Address ,District,PIN ,PANCardNo,Mobile1 ,Mobile2,OtherDetail,AgentCount, AgentCode,LevelRank,DateAdded ,Agency,SeniorAgentID )
                    VALUES(@State, @StateCode, @City, @CityCode, @FirstName,@LastName,@ParentName, @Relationship, @RelationshipCode, @DOB,@Age,@Address ,@District,@PIN ,@PANCardNo,@Mobile1 ,@Mobile2,@OtherDetail,@NewAgentCount,  @AGENT_CODE,@LevelRank, GETDATE() ,@Agency,@SeniorAgentID )
            END
        SELECT @Count = SCOPE_IDENTITY();

     COMMIT TRANSACTION
     END TRY
     BEGIN CATCH
        IF (@Count = 0)
         BEGIN
            ROLLBACK TRANSACTION
         END
    END CATCH
    END

我正在尝试创建@NewAgentCount,它是最大AgentCount的+1和@AGENT_CODE,它是12个字符的格式。但这给了我在主题中提到的错误。 Plzzz帮助!!

1 个答案:

答案 0 :(得分:0)

尝试交换BEGIN TRYBEGIN TRANSACTION语句:

http://msdn.microsoft.com/en-us/library/ms175976.aspx(例B)