﻿USE [FabApprovalSystem]
GO
	/****** Object:  UserDefinedFunction [dbo].[fnGetApprovalFullNames]    Script Date: 11/21/2024 11:31:55 AM ******/
SET
	ANSI_NULLS ON
GO
SET
	QUOTED_IDENTIFIER ON
GO
	CREATE FUNCTION [dbo].[fnGetApprovalFullNames] (
		@IssueID int,
		@DocumentTypeID int,
		@Separator varchar(10),
		@IncludeRole bit,
		@IncludeSubRole bit,
		@IncludePending bit,
		@IncludeApproved bit,
		@IncludeOthers bit
	) RETURNS varchar(max) AS BEGIN DECLARE @r varchar(max) DECLARE @t TABLE(u varchar(200))
INSERT INTO
	@t
SELECT
	@Separator + ISNULL(U.FirstName, '') + ' ' + ISNULL(U.LastName, '') + CASE
		WHEN @IncludeRole <> 0 THEN ' (' + A.RoleName + ')'
		ELSE ''
	END + CASE
		WHEN @IncludeSubRole <> 0 THEN ' (' + A.SubRole + ')'
		ELSE ''
	END
FROM
	Approval A
	LEFT OUTER JOIN Users U ON A.UserID = U.UserID
WHERE
	A.IssueID = @IssueID
	AND A.DocumentTypeID = @DocumentTypeID
	AND (
		(
			@IncludeOthers <> 0
			AND A.ItemStatus NOT IN (0, 1)
		)
		OR (
			@IncludePending <> 0
			AND A.ItemStatus = 0
		)
		OR (
			@IncludeApproved <> 0
			AND A.ItemStatus = 1
		)
	)
ORDER BY
	A.Step,
	U.FirstName,
	U.LastName
SELECT
	@r = (
		SELECT
			u + ''
		FROM
			@t FOR XML PATH('')
	) IF @r <> ''
SET
	@r = STUFF(@r, 1, LEN(@Separator), '') RETURN @r
END
GO