﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[LTUpdateLotTravelerHoldStep]    Script Date: 11/21/2024 11:29:05 AM ******/
SET
	ANSI_NULLS ON
GO
SET
	QUOTED_IDENTIFIER ON
GO
	-- =============================================
	-- Author:		<Author,,Name>
	-- Create date: <Create Date,,>
	-- Description:	<Description,,>
	-- =============================================
	CREATE PROCEDURE [dbo].[LTUpdateLotTravelerHoldStep] -- Add the parameters for the stored procedure here
	@LotTravHoldStepID INT,
	@NewLocation VARCHAR(50),
	@NewOperSequence NCHAR(10),
	@NewOperation VARCHAR(50) = NULL,
	@NewOperationDescription VARCHAR(100),
	@NewChangeInstructions VARCHAR(2000),
	@NewUpdatedBy INT,
	@Result INT = 0 OUTPUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET
	NOCOUNT ON;

DECLARE @SPNCurrentSeqForTheLot NCHAR(10) DECLARE @ProcessFlow NCHAR(10) DECLARE @LotNumber VARCHAR(50)
SET
	@LotNumber = (
		SELECT
			TOP 1 L.LotNumber
		FROM
			LTLotTravelerHoldSteps LH
			INNER JOIN LTLotTravelerRevisionAttrib LTA ON LH.LotTravelerRevisionID = LTA.ID
			INNER JOIN LTLot L ON LTA.LTLotID = L.ID
		WHERE
			LH.ID = @LotTravHoldStepID
	)
SET
	@ProcessFlow = (
		SELECT
			TOP 1 L.Process
		FROM
			LTLotTravelerHoldSteps LH
			INNER JOIN LTLotTravelerRevisionAttrib LTA ON LH.LotTravelerRevisionID = LTA.ID
			INNER JOIN LTLot L ON LTA.LTLotID = L.ID
		WHERE
			LH.ID = @LotTravHoldStepID
	) -- Get the Max Sequence# for this lot for the given location
SET
	@SPNCurrentSeqForTheLot = (
		SELECT
			MAX(SEQ)
		FROM
			vFAB2SPN_WO_RECORD WO
			INNER JOIN vSPNPDB_FLOWLOCS F ON WO.WO_PROCESS = F.PROCESS
			AND WO.WO_LOCATION = F.LOC
			AND WO.WO_OPER_NO = F.OPER
		WHERE
			WO_LOT_NO = @LotNumber
			AND WO_LOCATION = @NewLocation
			AND WO_PROCESS = @ProcessFlow
	) IF (@NewOperSequence > @SPNCurrentSeqForTheLot)
	OR (@SPNCurrentSeqForTheLot IS NULL) BEGIN
UPDATE
	LTLotTravelerHoldSteps
SET
	Location = @NewLocation,
	OperSequence = @NewOperSequence,
	Operation = @NewOperation,
	OperationDescription = @NewOperationDescription,
	ChangeInstructions = @NewChangeInstructions
WHERE
	ID = @LotTravHoldStepID
END
ELSE
SET
	@Result = -1
END
GO