varsha dodiya

varsha dodiya

  • NA
  • 407
  • 75.2k

sql stored procedure conditional

Aug 7 2014 8:14 AM
Hi everyone ,
 i m deducting some qty on basis of two conditions here ,these conditions are in loop.
ALTER PROCEDURE sp_UpdateStockForSale
@prodName varchar(40),
@stqty numeric(9,0),
@batchno varchar(40)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @S_en int;
DECLARE @savail Numeric(9,0);
DECLARE @ttavail numeric(9,0);
DECLARE @ttsold numeric(9,0);

While (@stqty > 0) BEGIN           (<- This is saying till sell qty does not become 0 )

Select @S_en=S_en,@ttavail=S_P_ttavail From STOCK Where S_P_ttavail > 0 And S_P_name = @prodName AND S_P_batchno=@batchno Order By S_en;

--If Sale Qty is more than Stock
IF (@ttavail < @stqty) BEGIN            (<- This is saying if avail qty is less than sale qty )
SET @stqty = @stqty - @ttavail;
SET @ttsold=@ttavail;
SET @ttavail = 0;

END
--If Sale Qty is less than STOCK
ELSE BEGIN                                           (<- This is saying if sale qty is less than avail qty )
SET @ttavail = @ttavail - @stqty;

SET @ttsold=@stqty
SET @stqty = 0;
END
Update STOCK Set S_P_ttavail = @ttavail, S_P_ttsold=@ttsold Where S_en=@S_en
END
END 
 ______________________________________________
 
 but i want to add one more condition here loop should continue deduction from avail qty row by row but when the last row of table comes is deduct remaining sale qty from the avail qty of that last row (if the last row is also not having sufficient qty  or 0 avail qty then result should come in minus (-).)
help me in this, how to get row number if that row is last row from result of all rows in select statement
 

Answers (10)