CREATE PROCEDURE AddExpirationOfGoods  @AutoId BIGINT, @Order BIT AS 
Begin
        DECLARE @Sender VARCHAR(5) 
        DECLARE @Reciver VARCHAR(5)
        DECLARE @GoodsCode VARCHAR(15) 
        DECLARE @TotalQty REAL; 
        DECLARE @WarehouseCode VARCHAR(5); 
        DECLARE @E_K_Code VARCHAR(15); 
        DECLARE @ExpQty REAL
        DECLARE @ExpDate DATETIME
        DECLARE @TmpQty REAL
		DELETE FROM Tmpexp WHERE Autoid = @AutoId

        SET @TmpQty = 0;

	    SELECT @Sender = sender , @Reciver = Reciver, @GoodsCode = K_Code, @TotalQty = K_Qty1 FROM TmpHavaleh WHERE AutoId = @AutoId


            SET @TmpQty = @TotalQty;

            DECLARE Cursor_Exp CURSOR FOR
            SELECT A_Code,
                   K_Code,
                   Exp_Date,
                   K_Qty
            FROM dbo.Exp_Date
            WHERE (A_Code = @Sender)
                  AND (K_Code = @GoodsCode)
            ORDER BY CASE WHEN @Order = 0 then Exp_Date END ,
			CASE WHEN @order =1 THEN Exp_Date END DESC 
            

            OPEN Cursor_Exp;

            FETCH NEXT FROM Cursor_Exp
            INTO @WarehouseCode,
                 @E_K_Code,
                 @ExpDate,
                 @ExpQty;

            IF @TmpQty > @ExpQty
               AND @ExpQty <> 0
                WHILE (@@FETCH_STATUS = 0 )
                BEGIN
                    IF @ExpQty <= @TmpQty
                    BEGIN
						INSERT INTO dbo.TmpExp
						(
							AutoId,
							K_Qty,
							Exp_Date
						)
						VALUES(@AutoId, @ExpQty, @ExpDate);
                        SET @TmpQty = @TmpQty - @ExpQty;
                    END;
                    ELSE
                    BEGIN
                INSERT INTO dbo.TmpExp
                (
                    AutoId,
                    K_Qty,
                    Exp_Date
                )
                VALUES(@AutoId, @TmpQty, @ExpDate);
                        SET @TmpQty = 0;
                    END;

                    IF @TmpQty = 0
                        BREAK;

                    FETCH NEXT FROM Cursor_Exp
                    INTO @WarehouseCode,
                         @E_K_Code,
                         @ExpDate,
                         @ExpQty;

                END;
            ELSE IF @ExpQty <> 0
            BEGIN
                INSERT INTO dbo.TmpExp
                (
                    AutoId,
                    K_Qty,
                    Exp_Date
                )
                VALUES(@AutoId, @TmpQty, @ExpDate);
            END;

            CLOSE Cursor_Exp;
            DEALLOCATE Cursor_Exp;


        IF(SELECT COUNT(*) FROM dbo.Exp_Date WHERE K_Qty = 0) > 0
            DELETE FROM dbo.Exp_Date WHERE K_Qty = 0;
End