Reputation: 5266
I need to get the no of records affected from the stored procedure. Based on this value I want to update the user whether the action got completed.
But my OUTPUT @RecordsAffected
parameter is always 0
How to get the no of records inserted in the transaction?
Followed How can I get the number of records affected by a stored procedure? and http://rusanu.com/2009/06/11/exception-handling-and-nested-transactions/
This is my procedure
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
Upvotes: 3
Views: 420
Reputation: 103585
You need to check @@ROWCOUNT
before you commit.
As @GSerg noted, this is because @@rowcount is supposed to return number of rows affected by the last statement, and commit is a statement that is documented to set @@rowcount to 0.
Upvotes: 4