SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

If Exists (Select * From dbo.sysobjects where id = object_id(N'[dbo].[qryMMSUpdateOrderGuideAfterVendorChange]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[qryMMSUpdateOrderGuideAfterVendorChange]
GO

CREATE PROCEDURE [dbo].[qryMMSUpdateOrderGuideAfterVendorChange]
AS
BEGIN

	create table #tempPriorVendors  ([EntityId] bigint,                      
						 [VendorId] bigint,
						 [PreviousVendorId] bigint,
						 [UsingInFORMVendorItemAssignment] bit)
                     
	INSERT INTO #tempPriorVendors(
		EntityId,
		VendorId,
		PreviousVendorId,
		UsingInFORMVendorItemAssignment)
	SELECT 
		ve.EntityID, 
		ve.VendorId, 
		ve.PreviousVendorId,
		1
	FROM tbVendorEntity ve with (nolock)
	WHERE VendorId <> PreviousVendorId 

	DECLARE @EntityId bigint
	DECLARE @VendorId bigint
	DECLARE @PreviousVendorId bigint
	DECLARE @UsingInFORMVendorItemAssignment bit

	DECLARE cur CURSOR FOR SELECT EntityID, VendorId, PreviousVendorId, UsingInFORMVendorItemAssignment
	FROM #tempPriorVendors  
	OPEN cur

	FETCH NEXT FROM cur INTO @EntityId, @VendorId, @PreviousVendorId, @UsingInFORMVendorItemAssignment

	WHILE @@FETCH_STATUS = 0 
	BEGIN 
		IF @UsingInFORMVendorItemAssignment = 1
		BEGIN
			UPDATE A 
			SET 
				A.DiscontinueDateOverridden = B.DiscontinueDateOverridden,
				A.DiscontinueDateOverrideEnabled = B.DiscontinueDateOverrideEnabled
			FROM tbVendorEntityItem as A
			JOIN tbVendorEntityItem B  on A.EntityID = B.EntityID and A.VendorCode = B.VendorCode
			WHERE A.EntityID = @EntityId and A.VendorID = @VendorId and B.VendorID = @PreviousVendorId
                                  
			SELECT @EntityId, @VendorId, @PreviousVendorId
		END

		-- Once we have copied these settings over (or skipped this), we no longer need to look at this any more
		UPDATE tbVendorEntity SET PreviousVendorId = NULL WHERE EntityID = @EntityId AND VendorID = @VendorId

	FETCH NEXT FROM cur INTO @EntityId, @VendorId, @PreviousVendorId, @UsingInFORMVendorItemAssignment
	END
	CLOSE cur    
	DEALLOCATE cur
	
	DROP Table #tempPriorVendors

END
GO