Я использовал рекурсивный CTE для получения родительских и дочерних отношений, но когда идентификаторы Parent и child одинаковы (исходя из 3 разных таблиц) CTE находится в бесконечном цикле.
Таблица процессов:
id name ParentName ParentID LevelId IndustryId``
1 Billing Serve 1 3 1
1 Serve CORE 1 2 1
1 CORE Retail 1 1 1
1 Retail NULL 0 0 1
Таблица инвентаризации:
RowID IndustryId BFuncName
1 1 Asses effectiveness of regulatory strategy
2 1 Brand and customer strategy
3 1 Brand Strategy
4 1 Billing
5 1 Brand management
6 1 Context & Content Management
7 1 Compensation Guidelines
8 1 Customer Contact
9 1 COMPLIANCE
Запрос:
DECLARE @CurrentRow int SET @CurrentRow=0
DECLARE @IndustryId INT set @IndustryId=1
WHILE @CurrentRow<=@RowsToProcess
BEGIN
;with inventorytableexpression as
(
select id, parentid,Name ,LevelId --------from Processes
from Process where Lower(Name) = (SELECT Lower(BFuncName)
FROM Inventory
WHERE RowID = 1 AND IndustryId=@IndustryId)
AND IndustryId=@IndustryId
union all
select C.id, C.parentid,c.Name,c.LevelId
from Process c join inventorytableexpression p on c.id = P.parentid AND IndustryId=@IndustryId
)
Select * from inventorytableexpression option (maxrecursion 0)
SET @CurrentRow=@CurrentRow+1
END
Результаты:
id parentid Name LevelId
1 1 Billing 3
1 1 Serve 2
1 1 CORE 1
1 0 Retail 0