---
title: "DB2利用syscat.references递归查出他的所有关联表"
author: "luzl"
date: "2011-06-22T23:50:48Z"
tags: []
categories: ["数据库"]
slug: "db2-syscat-references"
draft: false
lastmod: "2011-06-23T12:52:16Z"
id: 1101730
url: "https://luzl.iteye.com/blog/1101730"
---

找出所有的父表：

```java

With reftables(reftabname,PRIORITY) as(
Select reftabname,1 from syscat.references as refx where refx.tabname='PROJECT'
union all
Select ref2.reftabname,reftables.PRIORITY+1 from reftables,syscat.references ref2 where reftables.reftabname=ref2.tabname
)
Select * from reftables ORDER BY PRIORITY DESC;

```


找出所有的子表

```java

With reftables(tabname,PRIORITY) as(  
Select tabname,1 from syscat.references as refx where refx.reftabname='PROJECT'  
union all  
Select ref2.tabname,reftables.PRIORITY+1 from reftables,syscat.references ref2 where reftables.tabname=ref2.reftabname and  reftables.PRIORITY<2
)  
Select distinct * from reftables ORDER BY PRIORITY DESC;

```

其中
```java
reftables.PRIORITY<2
```
是用来控制层数，子表找到第几层！