我有一个叫Property2列的表PropertyRSN,ParentPropertyRSN
数据
propertyRSN | parentpropertyRSN
19 | 3
18 | 6
27 | 7
12 | 9
13 | 9
16 | 12
WITH tempTable(PLRSN, PRSN) AS (
SELECT PropertyRSN, Property.ParentPropertyRSN
FROM Property
WHERE PropertyRSN = 16
UNION ALL
SELECT nplus1.PropertyRSN, nplus1.ParentPropertyRSN
FROM Property as nplus1, tempTable
WHERE tempTable.prsn = nplus1.PropertyRSN
)
SELECT PLRSN, PRSN
FROM tempTable
结果
PLRSN | PRSN
16 | 12
12 | 9
9 | NULL
问题-我无法理解temTable查询如何获取包含数据的行9 | NULL?我也无法理解如何在方括号内使用TemTable?
================================================== ===================
create table property (propertyRSN int, ParentPropertyRSN int);
Insert into property (propertyRSN, ParentPropertyRSN) values (19,3);
Insert into property (propertyRSN, ParentPropertyRSN) values (18,6);
Insert into property (propertyRSN, ParentPropertyRSN) values (27,7);
Insert into property (propertyRSN, ParentPropertyRSN) values (12,9);
Insert into property (propertyRSN, ParentPropertyRSN) values (13,9);
Insert into property (propertyRSN, ParentPropertyRSN) values (16,12);
您的CTE恰好是递归 CTE,我会选择使用显式联接来编写它:
WITH tempTable (PLRSN, PRSN) AS (
SELECT PropertyRSN, Property.ParentPropertyRSN
FROM Property
WHERE PropertyRSN = 16
UNION ALL
SELECT nplus1.PropertyRSN, nplus1.ParentPropertyRSN
FROM Property AS nplus1
INNER JOIN tempTable t ON t.prsn = nplus1.PropertyRSN
)
SELECT PLRSN, PRSN FROM tempTable;
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。