【问题标题】:Getting No of records inserted in Transaction获取事务中插入的记录数
【发布时间】:2013-08-05 04:57:24
【问题描述】:

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

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

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

关注How can I get the number of records affected by a stored procedure?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

【问题讨论】:

  • 在提交前尝试移动SET @RecordsAffected = @@ROWCOUNT
  • @Blorgbeard,是的,它正在工作。谢谢。但是为什么在COMMIT 之后它不起作用?有什么想法吗?
  • @Billa 显然是因为@@rowcount 应该返回受最后一条语句影响的行数,而commitdocumented@@rowcount 设置为0 的语句。跨度>

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


【解决方案1】:

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

作为@GSerg noted,这是因为@@rowcount 应该返回受最后一条语句影响的行数,而commit 是documented 将@@rowcount 设置为0 的语句。

【讨论】:

    猜你喜欢
    • 2015-01-07
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多