Hi
I have below code . It returns success = false though record is inserted.When i comment below 2 lines then it works o.k
IF @@ROWCOUNT = 0
SET @Success = 0
ALTER PROCEDURE [dbo].[sp_Department]
@Action VARCHAR(1)
,@DocEntryNo int = Null
,@Description VARCHAR(50) = NULL
,@ShortName VARCHAR(15) = NULL
,@Status bit = NULL
,@Success BIT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
--INSERT
IF @Action = 'I'
BEGIN
INSERT INTO dbo.Department(Description,ShortName,status,createdby,createdon,updatedby,updatedon)
VALUES (@Description,@ShortName,1,1,GETDATE(),1,GETDATE())
SET @Success = 1
END
--DELETE
IF @Action = 'D'
BEGIN
UPDATE dbo.Department
SET status = 0 , updatedon = GETDATE(),updatedby = 1 WHERE docentry = @DocEntryNo
SET @Success = 1
END
IF @@ROWCOUNT = 0
SET @Success = 0
END
Thanks
Amit MohantyPosted Aug 20, 2024, 9:34 AM
The issue you're encountering is due to the scope of
@@ROWCOUNT. When@@ROWCOUNTis evaluated after the conditional logic forINSERTorUPDATE, it might not behave as intended because of the flow of the stored procedure. Check the below one:Jignesh KumarPosted Aug 20, 2024, 9:38 AM
Hello Ramco,
The better way you can write this way,
Naimish MakwanaPosted Aug 20, 2024, 9:35 AM
The issue you’re encountering is due to the placement of the
IF @@ROWCOUNT = 0check. This check is executed after both theINSERTandUPDATEstatements, and it will set@Successto 0 if the last statement did not affect any rows.To fix this, you should move the
IF @@ROWCOUNT = 0check inside each conditional block (IF @Action = 'I'andIF @Action = 'D'). This way, it will only check the@@ROWCOUNTimmediately after the relevantINSERTorUPDATEstatement. Here’s how you can modify your stored procedure:This way, the
@Successvariable is set based on whether theINSERTorUPDATEstatement affected any rows.Thanks