
CREATE PROCEDURE  [dbo].[EShop_FactorIncrementalReduction]
    @FactorId BIGINT,
    @PaymentId SMALLINT,
	@PostingId SMALLINT,
    @Amount1 MONEY,
	@Amount2 MONEY,
    @CustomerId UNIQUEIDENTIFIER,
	@Mobile varchar(20)
AS
DECLARE @Type Flag,
        @ActCode SMALLINT,
        @MaxPrice MONEY,
        @MaxPercent REAL,
		@CCode NVARCHAR(5),
        @Name NVARCHAR(MAX);
SELECT @Name = Name,
       @ActCode = CAST(Act_Code AS SMALLINT),
       @Type = Type,
       @MaxPercent = Max_Percent,
       @MaxPrice = Max_Price
FROM dbo.Over_Under
WHERE AutoId in( @PaymentId,@PostingId );

IF @Type is NULL
begin
	SET @Type = 0
END



set @CCode = '10000'
    SELECT  @CCode = Guy_Code
    FROM   dbo.Guy
    WHERE  mobile = @Mobile
INSERT dbo.Tmp_Over_Under_Factor
(
    Id_Havaleh,
    Name,
    Code_Over_Under,
    Type,
    Price,
    Act_Code,
    Guy_Code,
    Max_Price,
    Max_percent
)

SELECT @FactorId,
       Name,
	   Autoid,
	   0,
	   @Amount1,
       CAST(Act_Code AS SMALLINT),
	   @CCode,
       Max_Percent,
       Max_Price
FROM dbo.Over_Under
WHERE AutoId =@PaymentId
union 
SELECT @FactorId,
       Name,
	   Autoid,
	   1,
	   @Amount2,
       CAST(Act_Code AS SMALLINT),
	   @CCode,
       Max_Percent,
       Max_Price
FROM dbo.Over_Under
WHERE AutoId =@PostingId








