﻿USE [FabApprovalSystem]
GO
	/****** Object:  StoredProcedure [dbo].[_8DGetD5D6_CAList]    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].[_8DGetD5D6_CAList] -- Add the parameters for the stored procedure here
	@CANo INT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
SET
	NOCOUNT ON;

-- Insert statements for procedure here
SELECT
	CA.ID,
	CA.CANo,
	CorrectiveAction,
	Result,
	ECNLinks,
	ResponsibilityOwnerID,
	ResponsibilityOwnerID AS CurrentResponsibilityOwnerID,
	ECD,
	ImplementedDate,
	ImprovesWhat,
	D5Complete,
	D6Validated,
	CASE
		WHEN CA.CARequired = 1 THEN 'Yes'
		ELSE 'No'
	END AS CARequired,
	CA.AssignedDate,
	CA.Approved AS Approved,
	ImpID.ImpID AS ImprovementID,
	Imp.Improvement AS Improvement,
	U.FirstName + ' ' + U.LastName AS ResponsibilityOwnerName,
	FL.FileNames AS AttachmentLinks,
	CASE
		WHEN CA.Type = 1 THEN 'Corrective'
		WHEN CA.Type = 2 THEN 'Preventitive'
	END AS ActionType
FROM
	_8D_D5D6CorrectiveAction CA
	LEFT JOIN (
		SELECT
			DISTINCT CA1.ID,
			STUFF (
				(
					SELECT
						DISTINCT ',' + LTRIM(
							RTRIM(CAST(D5D6CA.D5D6ImprovementID AS VARCHAR(350)))
						)
					FROM
						_8D_D5D6CorrectiveAction CA
						INNER JOIN _8D_D5D6ImprovemntByCA D5D6CA ON CA.ID = D5D6CA.D5D6CAID
					WHERE
						CA.ID = CA1.ID FOR XML PATH('')
				),
				1,
				1,
				''
			) AS ImpID
		FROM
			_8D_D5D6CorrectiveAction CA1
	) AS ImpID ON CA.ID = ImpID.ID
	LEFT JOIN (
		SELECT
			DISTINCT CA1.ID,
			STUFF (
				(
					SELECT
						DISTINCT ',' + LTRIM(RTRIM(CAST(D5D6.Improvement AS VARCHAR(350))))
					FROM
						_8D_D5D6CorrectiveAction CA
						INNER JOIN _8D_D5D6ImprovemntByCA D5D6CA ON CA.ID = D5D6CA.D5D6CAID
						INNER JOIN _8D_D5D6Improvement D5D6 ON D5D6CA.D5D6ImprovementID = D5D6.ID
					WHERE
						CA.ID = CA1.ID FOR XML PATH('')
				),
				1,
				1,
				''
			) AS Improvement
		FROM
			_8D_D5D6CorrectiveAction CA1
	) AS Imp ON CA.ID = Imp.ID
	LEFT JOIN (
		SELECT
			DISTINCT CA.ID,
			STUFF (
				(
					SELECT
						DISTINCT ',' + CAST(REPLACE(A1.FileName, ',', '') AS varchar(512)) + '~' + CAST(A1.FileGuid AS varchar(512))
					FROM
						_8DCAAttachment A1
					WHERE
						A1.D5D6ID = CA.ID
						AND Section = 'D5' FOR XML PATH('')
				),
				1,
				1,
				''
			) AS FileNames
		FROM
			_8D_D5D6CorrectiveAction CA
	) AS FL ON CA.ID = FL.ID
	LEFT JOIN Users U ON CA.ResponsibilityOwnerID = U.UserID
WHERE
	CA.CANo = @CANo
END
GO