3

我需要获取受存储过程影响的记录数。基于此值,我想更新用户操作是否已完成。

但我的 OUTPUT@RecordsAffected参数始终为 0

如何获取事务中插入的记录数?

已关注如何获取受存储过程影响的记录数?http://rusanu.com/2009/06/11/exception-handling-and-nested-transactions/

这是我的程序

ALTER PROCEDURE [dbo].[SaveRoleFeatures]          
(        
@RoleId INT,        
@SelectedFeatures AS IdInt READONLY,
@RecordsAffected INT OUTPUT      
)       
AS      

BEGIN  

set nocount on;

DECLARE     @ErrorCode  int  
SELECT @ErrorCode = @@ERROR
declare @trancount int;
set @trancount = @@trancount;

BEGIN TRY     

 BEGIN TRAN

     DELETE FROM RoleXFeature WHERE RoleIid= @RoleId  

     INSERT RoleXFeature      
      (      
       RoleIid,      
       FeatureId,      
       IsDeleted  
      )      
      SELECT      

       @RoleId,      
       Id,
       0    

      FROM  @SelectedFeatures 

COMMIT TRAN

              SET @RecordsAffected = @@ROWCOUNT

  END TRY

  BEGIN CATCH

declare @error int, @message varchar(4000), @xstate int;
    select @error = ERROR_NUMBER(),
             @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
    if @xstate = -1
        rollback;
    if @xstate = 1 and @trancount = 0
        rollback
    if @xstate = 1 and @trancount > 0
        rollback transaction SaveRoleFeatures;

    raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
    return;

  END CATCH


  END
4

1 回答 1

4

您需要@@ROWCOUNT在提交之前进行检查。

正如@GSerg 所指出的,这是因为@@rowcount 应该返回受最后一条语句影响的行数,而commit 是一个记录将@@rowcount 设置为0 的语句。

于 2014-07-06T20:02:43.500 回答