DROP PROCEDURE CARGA_TMP_IN_COMPETITIONPRICE_PROC
GO
CREATE PROCEDURE CARGA_TMP_IN_COMPETITIONPRICE_PROC
( 	@SITEID		UD_IDSITE,
	@DATEPROCE	UD_FECHA,
	@CORRNBR	INT
)
AS
BEGIN
	BEGIN TRAN
	
	DECLARE @INVTIDSKU	UD_IDCORPORATIVO
	DECLARE @CODFAMFUEL	UD_CATEGORY

	DECLARE @PRICECURRENT	UD_PRECIO
	DECLARE @PRICECURRENT2	UD_PRECIO
	DECLARE @PRICEPREVIOUS	UD_PRECIO	


	SET @CODFAMFUEL=(SELECT CATEGORYFUEL FROM OP_SETUP)


	DECLARE CUR_CTRLPRICE	CURSOR	
	FOR 	SELECT INVTIDSKU FROM IN_INVENTORY
		WHERE CLASSID=@CODFAMFUEL
		ORDER BY INVTIDSKU
	OPEN CUR_CTRLPRICE
   	FETCH NEXT FROM CUR_CTRLPRICE INTO @INVTIDSKU

      	WHILE @@FETCH_STATUS=0
        BEGIN    

		SET @PRICECURRENT=ISNULL((SELECT SLS_PRICE FROM IN_INVENTORYDAT WHERE SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU),0)
		SET @PRICEPREVIOUS=ISNULL((SELECT PRICEPREVIOUS FROM IN_COMPETITIONPRICE WHERE SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU AND DATEPROCE=(SELECT MAX(DATEPROCE) FROM IN_COMPETITIONPRICE WHERE DATEPROCE<@DATEPROCE)),0)
		SET @PRICECURRENT2=ISNULL((SELECT PRICECURRENT FROM IN_COMPETITIONPRICE WHERE SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU AND DATEPROCE=(SELECT MAX(DATEPROCE) FROM IN_COMPETITIONPRICE WHERE DATEPROCE<@DATEPROCE)),0)

		IF(@PRICECURRENT!=@PRICECURRENT2)
		BEGIN
			SET @PRICEPREVIOUS=@PRICECURRENT2
		END  

		INSERT INTO TMP_IN_COMPETITIONPRICE(CORRNBR,SITEID,DATEPROCE,INVTIDSKU,PRICESUGGESTED,PRICECURRENT,PRICEPREVIOUS) 
		VALUES(@CORRNBR,@SITEID,@DATEPROCE,@INVTIDSKU,0,@PRICECURRENT,@PRICEPREVIOUS)

    		FETCH NEXT FROM CUR_CTRLPRICE INTO  @INVTIDSKU
        
      	END /* Termina while */

	COMMIT TRAN
  	CLOSE CUR_CTRLPRICE
  	DEALLOCATE CUR_CTRLPRICE

	RETURN(0)
END 



