﻿USE [FabApprovalSystem]
GO
    /****** Object:  UserDefinedFunction [dbo].[fn_GetMRBs]    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].[fn_GetMRBs] () RETURNS TABLE AS RETURN (
        -- Add the SELECT statement with parameter references here
        -- M_Suffix
        SELECT
            'MRB' AS DocumentType,
            'MRB' AS SubDoc,
            M.MRBNumber AS IssueID,
            M.MRBNumber AS DocID,
            M.SubmittedDate IssueDate,
            SQ.LotNo AS LotNos,
            pdg.Names AS 'PendingApprovers',
            Title,
            M.IssueDescription,
            U.FirstName + ' ' + U.LastName AS Originator,
            SubmittedDate,
            CloseDate
        FROM
            MRB M
            LEFT JOIN Users U ON M.OriginatorID = U.UserID
            LEFT JOIN (
                SELECT
                    DISTINCT M.MRBNumber,
                    STUFF (
                        (
                            SELECT
                                '/' + CAST(L.LotNumber AS varchar(512))
                            FROM
                                MRBLot L
                            WHERE
                                L.MRBNumber = M.MRBNumber FOR XML PATH('')
                        ),
                        1,
                        1,
                        ''
                    ) AS LotNo
                FROM
                    MRB M
            ) AS SQ ON m.MRBNumber = SQ.MRBNumber
            LEFT JOIN (
                SELECT
                    DISTINCT m.MRBNumber,
                    STUFF (
                        (
                            SELECT
                                '/' + CAST(U.FirstName AS varchar(50)) + ' ' + CAST(U.LastName AS varchar(50))
                            FROM
                                Approval A
                                INNER JOIN Users U ON A.UserID = U.UserID
                            WHERE
                                A.DocumentTypeID = 2
                                AND A.IssueID = m.MRBNumber
                                AND ItemStatus = 0 FOR XML PATH('')
                        ),
                        1,
                        1,
                        ''
                    ) AS Names
                FROM
                    MRB m
            ) AS pdg ON M.MRBNumber = pdg.MRBNumber
    )
GO