﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE FUNCTION [dbo].[fds__getRequestTreeIds]
(	
	@srqid bigint
)
RETURNS TABLE 
AS
RETURN 
(
	with sp as (
		SELECT DISTINCT [parentid] = CASE WHEN ISNULL([parentservicerequestid],0) = 0 THEN [id] ELSE [parentservicerequestid] END FROM [dbo].[mfr__servicerequests] as _s where _s.[Id] = @srqid OR _s.[ParentServiceRequestId] = @srqid
	)
	SELECT DISTINCT r.[Id] from [dbo].[mfr__servicerequests] as r JOIN sp on r.[Id] = sp.[parentid] OR r.[ParentServiceRequestId] = sp.[parentid] and ISNULL(sp.parentid,0) > 0
)