@JOBID int, @SCHID int, @MAXLEVELS int 
AS
BEGIN
SET NOCOUNT ON
SET XACT_ABORT ON

/*
declare @JOBID int
declare @SCHID int
declare @MAXLEVELS int
Set @JOBID = 1
Set @SCHID = 1
Set @MAXLEVELS = 100


exec [dbo].[EZViewer_CA7_Get_Graph_Backward] 1000 , 1, 100 
*/


		  DECLARE @StartNode int
		  DECLARE @UniqueID int = 0
		  DECLARE @RC int = 0
		  DECLARE @LEVEL int = 1
		  
          DECLARE @Rn INT; 
          DECLARE @JobTrgId INT; 
          DECLARE @OutSchidId INT;
          DECLARE @Lv INT;
          DECLARE @Pathid INT;
          DECLARE @i INT;
          DECLARE @JobSrcId INT;

		  SET @StartNode = @JOBID
		  SET @MAXLEVELS  = COALESCE(@MAXLEVELS, 100)
		  IF @MAXLEVELS > 1000 SET @MAXLEVELS = 1000


		  IF OBJECT_ID('tempdb..#Discovered') IS NOT NULL DROP TABLE #Discovered
		  CREATE TABLE #Discovered (
								src int,
								tgt int,
								ord int,
								ssid int,
								tsid int,
								pathid int )
							 
            CREATE NONCLUSTERED INDEX ncidx12 ON #Discovered (src ASC, tgt ASC)



		   IF OBJECT_ID('tempdb..#TempDiscovered') IS NOT NULL DROP TABLE #TempDiscovered
		   CREATE TABLE #TempDiscovered (
							 rn  INT IDENTITY(1,1) NOT NULL,
							 src int,
							 tgt int,
							 ord int,
							 ssid int,
							 tsid int,
							 pathid int )

            CREATE NONCLUSTERED INDEX ncidx13 ON #TempDiscovered (PathID ASC) INCLUDE (rn)



		  IF OBJECT_ID('tempdb..#Path') IS NOT NULL DROP TABLE #Path
		  CREATE TABLE #Path (
						  firstLevel int,
						  dupsch int,
						  pathid int,
						  src int,
						  tgt int,
						  ord int,
						  ssid int,
						  tsid int   )

		 CREATE CLUSTERED INDEX cidx14 ON #Path (PathID ASC, Ord ASC)


		  IF OBJECT_ID('tempdb..#withdsn') IS NOT NULL DROP TABLE #withdsn
		  CREATE TABLE #withdsn (
			 dsn varchar(255),
			 indsn int,
			 outdsn int,
			 pathid int,
			 src int,
			 tgt int,
			 ord int,
			 ssid int,
			 tsid int )

		CREATE CLUSTERED INDEX cidx15 ON #withdsn (PathID ASC, Ord ASC)	 
            

	    INSERT INTO #Discovered (src, tgt, ord, pathid) VALUES (@StartNode, null, 0, @UniqueID)
	    INSERT INTO #Path (src, tgt, ord, pathid) VALUES (@StartNode, null, 0,  @UniqueID)



--select * from CA7_Jobs
--select * from CA7_SchedulesPerJob
--select * from CA7_JobsTriggeredByJobs
--select * from CA7_JobsTriggeredByDatasets

				SET @RC = 1
				WHILE @RC > 0 AND @MAXLEVELS > @LEVEL
				BEGIN
				    SET @LEVEL = @LEVEL + 1
				    SET @UniqueID = 1 + (select max(pathid) from #Path)

				    INSERT INTO #TempDiscovered (src, tgt, ord, ssid, tsid, pathid)
				    SELECT e.TriggeredBy_JobID, 
						 e.JobID, 
						 MIN(d.ord) + 1, 
						 e.inSCHID,
						 e.outSCHID, 
						 d.pathid
				    FROM CA7_JobsTriggeredByJobs e 
					   INNER JOIN #Discovered d   ON d.src = e.JobID AND 
															   (    e.outSCHID = 0 
															     OR d.ssid = 0
																OR d.tsid is null
																OR d.ssid = e.outSCHID
															   )
				    WHERE NOT EXISTS (SELECT 1 
								  FROM #Discovered as dd
								  WHERE e.TriggeredBy_JobID = dd.src 
									    and e.JobID = dd.tgt
								 )
				    GROUP BY e.TriggeredBy_JobID, e.JobID, e.inSCHID, e.outSCHID, d.pathid
				    ORDER BY e.TriggeredBy_JobID

                   declare cc3 cursor 
                   for select rn,src,tgt,tsid,ord,pathid FROM #TempDiscovered
                   OPEN cc3
                   FETCH NEXT FROM cc3 INTO @Rn, @JobSrcId, @JobTrgId, @OutSchidId, @Lv, @Pathid;
        
                   WHILE @@FETCH_STATUS = 0  
                   BEGIN 
                        SET @i = 0;
                        IF OBJECT_ID('EZViewer_CA7_Validate_SCHID') IS NOT NULL
                            BEGIN
                                exec @i = EZViewer_CA7_Validate_SCHID @StartNode, @JobSrcId, @JobTrgId, @OutSchidId, @lv, @Pathid 
                            END
        
                        if (@i = 0)
                        BEGIN
                            delete from #TempDiscovered where rn = @Rn
                        END
        
                        FETCH NEXT FROM cc3 INTO @Rn, @JobSrcId, @JobTrgId, @OutSchidId, @Lv, @Pathid;
                    END;
        
                    CLOSE cc3
                    DEALLOCATE cc3
        
                    SET @RC = (select count(*) from #TempDiscovered)

					   INSERT INTO #Path (pathid, src, tgt, ord, ssid, tsid)
					   SELECT td.rn + @UniqueID as pathid, p.src, p.tgt, p.ord, p.ssid, p.tsid
					   FROM #Path p
							 INNER JOIN #TempDiscovered td on p.pathid = td.pathid
                       GROUP BY td.rn, p.src, p.tgt, p.ord, p.ssid, p.tsid


					   DELETE p
					   FROM #Path p
					        INNER JOIN #TempDiscovered td ON p.pathid = td.pathid
					

					   insert into #Path (pathid, src, tgt, ord, ssid, tsid)
					   select @UniqueID + td.rn, td.src, td.tgt, td.ord, td.ssid, td.tsid
					   from #TempDiscovered td


					   insert into #Discovered (src, tgt, ord, ssid, tsid, pathid)
					   select td.src, td.tgt, td.ord, td.ssid, td.tsid, @UniqueID + td.rn 
					   from #TempDiscovered td


					  TRUNCATE TABLE #TempDiscovered
				END






--select * from #Path order by pathid, ord desc
    update #Path 
    set firstLevel = ord
    where ord = (select MAX(ord) from #Path as p
                    where p.pathid = #Path.pathid
                    group by p.pathid)


     set @UniqueID = 1 + (select max(pathid) from #Path)

    insert into #Path (firstLevel, dupsch, pathid, src, tgt, ord, ssid, tsid)
    select td.firstLevel, pp.schid, @UniqueID + td.pathid + pp.schid, td.src, td.tgt, td.ord, td.ssid, td.tsid
    from #Path as td inner join(
    select p.pathid, p.src, spj.schid from #Path as p
	   inner join CA7_SchedulesPerJob as spj on spj.JobID = p.src
	   where p.firstLevel is not Null
    union
    select  p.pathid, p.src, case when tbd.outSCHID = 0 then tbd.inSCHID else tbd.outSCHID end
	   from #Path p inner join CA7_JobsTriggeredByDatasets as tbd on tbd.JobID = p.src
	   and p.firstLevel is not null and (
		  p.ssid = 0
		  or p.ssid is null
		  )
    )as pp on td.pathid = pp.pathid

--select * from #Path order by pathid, ord desc

--delete from #Path where dupsch is null and pathid in
--        (select p.pathid from #Path as p  where p.ssid = 0 and p.firstLevel is not Null)


	   update #Path set ssid = -dupsch
	    from (select p.pathid as pid, p.ord as o from #Path as p  where p.firstLevel is not Null)as ppp
	    where dupsch is not null and ssid = 0 and pathid = ppp.pid and ord = ppp.o

--select 'a', * from #Path order by pathid, ord desc

	   insert into #Path (firstLevel, dupsch, pathid, src, tgt, ord, ssid, tsid)
	   select  p.firstLevel,p.dupsch, p.pathid, p.src, p.tgt, p.ord, tbj.inSCHID, p.tsid
		  from #Path p inner join CA7_JobsTriggeredByJobs as tbj on tbj.TriggeredBy_JobID = p.src
		  and p.firstLevel = 0 and p.ssid is null


--select 'b',* from #Path order by pathid, ord desc

	   delete from #Path where firstLevel = 0 and ssid is null and dupsch is null

	   update #Path set ssid = -dupsch where ord = 0 and dupsch is not null and firstLevel is not null

--select * from #Path order by pathid, ord desc



        IF OBJECT_ID('tempdb..#tmpPaths') IS NOT NULL DROP TABLE #tmpPaths
	   CREATE TABLE #tmpPaths (    
						  Row INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
						  pathid int,
						  ord int,
						  ssid int,
						  tsid int)


	   INSERT INTO #tmpPaths (pathid, ord, ssid, tsid)
	   SELECT DISTINCT pathid, ord, ssid, tsid
	   FROM #Path 
	   ORDER BY pathid, ord DESC






  

			 --select * from #tmpPaths
			 declare @forcedSchid int
			 Declare @row int
			 Declare @mxrow int
			 Set @mxrow = (select MAX(Row) from #tmpPaths)
			 Declare @cpath int
			 Declare @opath int
			 Declare @cssid int
			 Declare @ctsid int
			 Declare @otsid int
			 Declare @mval int
			 Declare @cord int
			 Set @opath = -1
			 Set @cpath = -1
			 Set @forcedSchid = 0
			 Set @otsid = @forcedSchid
			 Set @mval = @forcedSchid
			 Set @row = 1

			 while (@row <= @mxrow)
			 begin

				select @cpath = t.pathid, @cord = t.ord, @cssid = t.ssid, @ctsid = t.tsid
				    from #tmpPaths as t where Row = @row
				if (@opath = -1) begin
				    Set @opath = @cpath
				    Set @otsid = @cssid
				    end
				if (@cpath <> @opath)
				   begin
				    Set @opath = @cpath
				    Set @otsid = @cssid
				    Set @mval = @forcedSchid
				   end

				    if (@cssid = 0)
					  begin
					    update #Path set ssid = @mval where pathid = @cpath and ord = @cord
					  end
				    else
					   begin
					    if (abs(@cssid) <> abs(@otsid))
						   begin
							 delete from #Path where pathid = @cpath and ord > @cord
						   end
					    else
						  Set @mval = -abs(@cssid)
					   end
				    if (@ctsid = 0)
					   begin
						update #Path set tsid = @mval where pathid = @cpath and ord = @cord
					   end
				    else
					   begin
						  Set @mval = -abs(@ctsid)
						  Set @otsid = @ctsid
					   end

				Set @row = @row + 1
			 end





--select * from #Path order by pathid, ord desc

	   insert into #withdsn (dsn, indsn, outdsn, pathid, src, tgt, ord, ssid, tsid)
	   select distinct jtd.DSN, jtd.inSCHID, jtd.outSCHID, p.pathid, p.src, p.tgt, p.ord, p.ssid, p.tsid
	   from #Path as p
		  left join CA7_JobsTriggeredByDatasets as jtd on jtd.JobID = p.src
			 and jtd.inSCHID = @SCHID
			 and (jtd.outSCHID = abs(p.ssid) or jtd.outSCHID = 0 or p.ssid = 0 or p.ssid is null)



	   SELECT p.pathid, p.src, p.tgt, p.ord, p.ssid, p.tsid, p.dsn, p.indsn, p.outdsn 
	   FROM #withdsn p
	   WHERE pathid IN
				    (select pathid 
					from #withdsn pp
					 where abs(ssid) = @SCHID or abs(tsid) = @SCHID or dsn is not null)
	   ORDER BY p.pathid, p.ord desc




	   DROP TABLE #withdsn
	   DROP TABLE #Discovered
	   DROP TABLE #Path
	   DROP TABLE #TempDiscovered
	   DROP TABLE #tmpPaths

END