﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[GetMRBsFromSPN]    Script Date: 11/21/2024 11:29:04 AM ******/
SET
	ANSI_NULLS ON
GO
SET
	QUOTED_IDENTIFIER ON
GO
	CREATE PROCEDURE [dbo].[GetMRBsFromSPN] @LotNo VARCHAR(10) AS BEGIN DECLARE @ParentLotNo VARCHAR(10) DECLARE @sql NVARCHAR(MAX) DECLARE @wp_lot_from TABLE(WP_LOT_FROM VARCHAR(10)) DECLARE @results TABLE(MRBNumber INT) DECLARE @finalresults TABLE(MRBNumber INT, DispoType CHAR(1)) -- Get the parent Lot	
SET
	@sql = N 'SELECT WP_LOT_FROM FROM OPENQUERY(FAB2SPN, ''SELECT WP_LOT_FROM FROM WP_RECORD WHERE WP_DIRECT_KEY = ''''3002' + @LotNo + ''''' '')'
DELETE FROM
	@wp_lot_from
INSERT INTO
	@wp_lot_from EXEC sp_executesql @sql
SET
	@ParentLotNo = (
		SELECT
			TOP 1 WP_LOT_FROM
		FROM
			@wp_lot_from
	) DECLARE @MRB VARCHAR(10) = '%MRBINFO%'
SET
	@sql = FORMATMESSAGE(
		'SELECT  DISTINCT LEFT(WT_COMMENT, 4) AS MRBNumber  FROM OPENQUERY(FAB2SPNTESTMJ, ' + '''SELECT WT_COMMENT ' + 'FROM WT_RECORD ' + 'WHERE WT_WP_DIRECT_KEY = ''''3002%s ''''  AND WT_VERB LIKE ''''%s'''' '') ',
		@LotNo,
		@MRB
	)
DELETE FROM
	@results
INSERT INTO
	@results EXEC sp_executesql @sql DECLARE @MRBNumber INT DECLARE MRBList CURSOR FOR
SELECT
	MRBNumber
FROM
	@results OPEN MRBList FETCH NEXT
FROM
	MRBList INTO @MRBNumber WHILE @ @FETCH_STATUS = 0 BEGIN -- Only process if the @LotNo & the MRB record is not present
	IF (
		SELECT
			COUNT(*)
		FROM
			MRBLot
		WHERE
			MRBNumber = @MRBNumber
			AND LotNumber = @LotNo
	) = 0 BEGIN -- Get the Dispo of the Parent Lot
	IF (
		SELECT
			COUNT(*)
		FROM
			MRBLot
		WHERE
			MRBNumber = @MRBNumber
			AND LotNumber = LTRIM(RTRIM(@ParentLotNo))
	) > 0 BEGIN
INSERT INTO
	@finalresults
SELECT
	MRBNumber,
	DispoType
FROM
	MRBLot
WHERE
	MRBNumber = @MRBNumber
	AND LotNumber = LTRIM(RTRIM(@ParentLotNo))
END
ELSE BEGIN
INSERT INTO
	@finalresults
VALUES
	(@MRBNumber, NULL)
END
END FETCH NEXT
FROM
	MRBList INTO @MRBNumber
END CLOSE MRBList DEALLOCATE MRBList
SELECT
	*
FROM
	@finalresults
END
GO