CREATE PROCEDURE [dbo].[AllDownlinksCompanyCorp] AS
SET NOCOUNT ON

Create Table #Temp3 (CustomerNumber int NOT NULL,
                                    CustomerTypeNumber int NOT NULL)

  Insert  #Temp3(CustomerNumber,CustomerTypeNumber)
  select CustomerNumber,CustomerTypeNumber from Customer WITH (NOLOCK) where (CustomerTypeNumber=2 or CustomerTypeNumber=6) and CustomerNumber in
  (Select CustomerNumber from CustomerLinks WITH (NOLOCK) where LinkTypeNumber=0 and CustomerLinkNumber in (select CustomerNumber from #FoundValues where CustomerTypeNumber=4 ) UNION ALL
  Select CustomerLinkNumber from CustomerLinks WITH (NOLOCK) where LinkTypeNumber=0 and CustomerNumber in  (select CustomerNumber from #FoundValues where CustomerTypeNumber=4 ))
  
 Insert #FoundValues(CustomerNumber,CustomerTypeNumber)
  select CustomerNumber,CustomerTypeNumber from Customer WITH (NOLOCK) where CustomerTypeNumber=1 and CustomerNumber in
  (Select CustomerNumber from CustomerLinks WITH (NOLOCK) where LinkTypeNumber=0 and CustomerLinkNumber in (select  CustomerNumber from #Temp3 where CustomerTypeNumber=2 ) UNION ALL
  Select CustomerLinkNumber from CustomerLinks WITH (NOLOCK) where LinkTypeNumber=0 and  CustomerNumber in  (select  CustomerNumber from #Temp3 where CustomerTypeNumber=2))

 Insert #FoundValues(CustomerNumber,CustomerTypeNumber)
  Select * from #Temp3

DROP TABLE #Temp3