我正在使用 SQL Server 2012
LOCATIONDETAIL 表
OID LOCATIONNAME PARENTID
1 GLOBAL 0
2 NORTH 1
3 SOUTH 1
4 NORTH1 2
5 SOUTH1 3
LOCATIONSITECONFIG 表
OID LOCATIONID SITENAME
1 2 TEST
我使用递归 CTE 查询
;WITH LOCALSITEHIERARCHY AS
(
SELECT A.OID
,A.PARENTOID
,CAST(A.LOCATIONNAME + ' ( ' + LSC.SITENAME + ' )' AS NVARCHAR(100)) AS NAME
,LSC.OID AS SITEOID
FROM LOCATIONDETAIL A
INNER JOIN LOCATIONSITECONFIG LSC
ON LSC.LOCATIONDETAILOID = A.OID
WHERE
LSC.SITENAME <> 'GLOBAL' AND LSC.RECSTATUS = 'A'
UNION ALL
SELECT
A.OID
,A.PARENTOID
,CAST(A.LOCATIONNAME AS NVARCHAR(100))
,LH.SITEOID
FROM LOCATIONDETAIL A
INNER JOIN LOCALSITEHIERARCHY LH ON A.PARENTOID = LH.OID
)
SELECT * FROM LOCALSITEHIERARCHY
NORTH 现在是 Global 中的一个单独站点。此查询以树结构返回 North 和 North 1,这是可以的。
当我将 Global 作为一个新站点时,我不想将 North 作为 Global 站点的一部分。
示例,添加名为 (NEWTEST) 的站点 2,即 Global
LOCATIONSITECONFIG 表
OID LOCATIONDETAILOID SITENAME
1 2 TEST
2 1 NEWTEST
上面的查询返回 Global , NORTH, NORTH1, SOUTH, SOUTH1 和 NORTH(TEST) AND NORTH1 (重复记录)
我希望查询返回 Global , NORTH (TEST), NORTH1, SOUTH, SOUTH1
如果孩子已经创建了站点,则查询应该忽略。请帮忙