CREATE PROCEDURE dbo.ProductPriceConvert @APacketType INT, @ACurrentPacketNumber INT, @APacketNumber INT, @ACurrentProductNumber INT, @AProductNumber INT, 
  @ADateTime DATETIME, @ALastPackageEndDate DATETIME, @ALastInserted INT OUTPUT AS
SET NOCOUNT ON

/*
IF @APacketType = 0
BEGIN
  PRINT '**************************'
  PRINT @ACurrentPacketNumber 
  PRINT @APacketNumber 
  --PRINT @ACurrentProductNumber 
  --PRINT @AProductNumber 
  PRINT @ADateTime 
  PRINT @ALastPackageEndDate
  PRINT @ALastInserted
END  
*/

IF @APacketNumber > 0
BEGIN
  IF @ALastPackageEndDate = 0
    SET @ALastPackageEndDate = @ADateTime 
  DECLARE @DoInsert BIT

  IF @ADateTime <> DATEADD(DAY, 1, @ALastPackageEndDate) OR @ACurrentProductNumber <> @AProductNumber OR ISNULL(@ALastInserted, 0) = 0 OR @ACurrentPacketNumber <> @APacketNumber
    SET @DoInsert = 1
  ELSE
    SET @DoInsert = 0
  
  IF @DoInsert = 1
  BEGIN
    IF NOT EXISTS (SELECT * FROM ProductPricePacket WHERE FK_ProductNumber = @AProductNumber AND FK_PacketNumber = @APacketNumber AND PacketType = @APacketType AND StartDate = @ADateTime AND EndDate = @ADateTime)
    BEGIN
      INSERT INTO ProductPricePacket (FK_ProductNumber, PacketType, StartDate, EndDate, FK_PacketNumber) VALUES (@AProductNumber, @APacketType, @ADateTime, @ADateTime, @APacketNumber)
      SET @ALastInserted = @@IDENTITY
    END  
  END
  ELSE
  BEGIN
    -- edit
    UPDATE ProductPricePacket SET EndDate = @ADateTime
    WHERE Id = @ALastInserted
  END  
END