SQL开发人员,我有一个计划不周的数据库作为任务,以学习有关SQL Server 2012的很多知识。
所以,有表Elem
:
+-----------+----+---+----------+------------+
|VERSION(PK)|NAME|KEY|PARENT_KEY|DIST_KEY(FK)|
+-----------+----+---+----------+------------+
|1 |a |12 |NULL |1 |
+-----------+----+---+----------+------------+
|2 |b |13 |12 |1 |
+-----------+----+---+----------+------------+
|3 |c |14 |13 |1 |
+-----------+----+---+----------+------------+
|4 |d |15 |12 |1 |
+-----------+----+---+----------+------------+
|5 |e |16 |NULL |1 |
+-----------+----+---+----------+------------+
|6 |e |17 |NULL |2 |
+-----------+----+---+----------+------------+
更新该行后,我需要检查element的父键,以不允许element自self之类。
当我删除该行时,我需要删除所有孩子以及孩子的孩子,等等。
问题是:
如何选择DIST的一个元素的所有“父母+祖父母+等等”?
我如何选择DIST元素中的所有“儿子+孙子+等”?
我读到有关CTE的解决方案的信息,但是我没有任何基础,甚至不知道那时如何使用CTE。
请帮忙!
谢谢。
我遇到了这个问题,我通过这种方式解决了问题
--all "parent + grandparent + etc" @childID Replaced with the ID you need
with tbParent as
(
select * from Elem where [KEY]=@childID
union all
select Elem.* from Elem join tbParent on Elem.[KEY]=tbParent.PARENT_KEY
)
SELECT * FROM tbParent
--all "sons + grandsons + etc" @parentID Replaced with the ID you need
with tbsons as
(
select * from Elem where [KEY]=@parentID
union all
select Elem.* from Elem join tbsons on Elem.PARENT_KEY=tbsons.[KEY]
)
SELECT * FROM tbsons
PS。我的英语不好。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句