我有一个数据库,其中表与其他表有关系,并建立一个n级层次结构
父表 - >儿童桌 - >大孩子桌等等。
因此,这意味着根父表的任何子表都可以是其他一些表的父表。这种关系可以有不同/多个层次结构。
现在,我希望对sys对象(例如sys.foreign_keys等)进行查询,以针对Parent表检索所有子表。 例如,我有以下相关表格
Select OBJECT_NAME(Parent.parent_object_id) ForeignKeyTable, OBJECT_NAME(Parent.referenced_object_id) PrimaryKeyTable, Parent.name
From sys.foreign_keys Parent
LEFT JOIN sys.foreign_keys Child
On Parent.referenced_object_id = Child.parent_object_id
Where OBJECT_NAME(Child.referenced_object_id) = 'PersonOrganisation' OR
OBJECT_NAME(Child.parent_object_id) = 'PersonOrganisation'
PersonOrganisation - >组织 - >服务 - > ServiceAttendants
因此,如果我需要获取PersonOrganisation的所有子表,那么它应该从Organization返回到ServiceAttendants的层次结构
如果我想获取Organization的子表,它应该从Services返回到ServiceAttendants的层次结构
我写了一个以下的查询。看起来不错,但我只是想再确认一下或者比这更好的查询方法。
答案 0 :(得分:0)
您可以使用这样的递归CTE:
;with x as (
select cast(object_name(parent_object_id) as varchar(max)) as name, parent_object_id, 0 as lvl
from sys.foreign_keys
where referenced_object_id = object_id('table_name')
union all
select cast(x.name + ' -> ' + object_name(f.parent_object_id) as varchar(max)), f.parent_object_id, lvl + 1
from sys.foreign_keys f
inner join x on x.parent_object_id = f.referenced_object_id
and x.parent_object_id <> f.parent_object_id
)
select name
from x