﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[GetLots]    Script Date: 11/21/2024 11:29:04 AM ******/
SET
	ANSI_NULLS ON
GO
SET
	QUOTED_IDENTIFIER ON
GO
	-- =============================================
	-- Author:		<Author,,Name>
	-- Create date: <Create Date,,>
	-- Description:	<Description,,>
	-- =============================================
	CREATE PROCEDURE [dbo].[GetLots] -- Add the parameters for the stored procedure here
	@IssueID INT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET
	NOCOUNT ON;

SELECT
	SQ.IssueIDs AS MRBsLinkedToLot,
	L.*,
	S.ReleaseCount,
	S.ScrapCount,
	LS.LotStatusOptionID,
	LS.LotStatusOption
FROM
	Lot L
	INNER JOIN LotStatusOption LS ON L.LotStatusOptionID = LS.LotStatusOptionID
	LEFT JOIN ScrapLot S ON L.LotNumber = S.LotNo
	AND L.IssueID = S.IssueID
	LEFT JOIN (
		SELECT
			DISTINCT L.LotID,
			STUFF (
				(
					SELECT
						DISTINCT ',' + CAST(ML.MRBNumber AS varchar(512))
					FROM
						MRBLot ML
					WHERE
						L.LotNumber = ML.LotNumber FOR XML PATH('')
				),
				1,
				1,
				''
			) AS IssueIDs
		FROM
			Lot L
	) AS SQ ON L.LotID = SQ.LotID
WHERE
	L.IssueID = @IssueID
END
GO