﻿USE [FabApprovalSystem]
GO
	/****** Object:  UserDefinedFunction [dbo].[fnGetMRB_SPN_HoldLots]    Script Date: 11/21/2024 11:31:55 AM ******/
SET
	ANSI_NULLS ON
GO
SET
	QUOTED_IDENTIFIER ON
GO
	-- =============================================
	-- Author:		<Author,,Name>
	-- Create date: <Create Date,,>
	-- Description:	<Description,,>
	-- =============================================
	CREATE FUNCTION [dbo].[fnGetMRB_SPN_HoldLots] (
		-- Add the parameters for the function here
		@MRBNumber INT
	) RETURNS TABLE AS RETURN (
		-- Add the SELECT statement with parameter references here
		SELECT
			L.LotNumber,
			MD.MRBNumber
		FROM
			MRBDispositionByMRB MD
			INNER JOIN MRBLot L ON MD.DispositionType = L.DispoType
			INNER JOIN MRB M ON M.MRBNumber = MD.MRBNumber
		WHERE
			CloseToQDBOptionID = 1
			AND L.MRBNumber = @MRBNumber
			AND MD.MRBNumber = @MRBNumber
			AND L.LotNumber + CONVERt(VARCHAR(10), MD.MRBNumber) NOT IN (
				SELECT
					LotNumber + CONVERt(VARCHAR(10), MRBNumber)
				FROM
					MRB_SPN_HoldFlagLot
			)
		UNION
		SELECT
			LotNumber,
			MRBNumber
		FROM
			MRB_SPN_HoldFlagLot
		WHERE
			LotNumber IN (
				SELECT
					DISTINCT L.LotNumber
				FROM
					MRBDispositionByMRB MD
					INNER JOIN MRBLot L ON MD.DispositionType = L.DispoType
					INNER JOIN MRB M ON M.MRBNumber = MD.MRBNumber
				WHERE
					CloseToQDBOptionID = 1
					AND L.MRBNumber = @MRBNumber
					AND MD.MRBNumber = @MRBNumber
					AND L.LotNumber + CONVERt(VARCHAR(10), MD.MRBNumber) NOT IN (
						SELECT
							LotNumber + CONVERt(VARCHAR(10), MRBNumber)
						FROM
							MRB_SPN_HoldFlagLot
					)
			)
	)
GO