我正在尝试使用以下递归 CTE 查询从下到上查找表的引用表
With CTE_ALL AS
(
SELECT
1 as TopLevel, c.CONSTRAINT_NAME, cu.TABLE_NAME AS ReferencingTable,
cu.COLUMN_NAME AS ReferencingColumn,ku.TABLE_NAME AS ReferencedTable,
ku.COLUMN_NAME AS ReferencedColumn
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS c
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cu
ON cu.CONSTRAINT_NAME = c.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku
ON ku.CONSTRAINT_NAME = c.UNIQUE_CONSTRAINT_NAME
where cu.TABLE_NAME = 'my table name'
Union All
SELECT
2 as BelowLevels, c.CONSTRAINT_NAME, cu.TABLE_NAME AS ReferencingTable,
cu.COLUMN_NAME AS ReferencingColumn,ku.TABLE_NAME AS ReferencedTable,
ku.COLUMN_NAME AS ReferencedColumn
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS c
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE cu
ON cu.CONSTRAINT_NAME = c.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku
ON ku.CONSTRAINT_NAME = c.UNIQUE_CONSTRAINT_NAME
INNER JOIN CTE_ALL CTE on CTE.ReferencedColumn = ku.COLUMN_NAME
and CTE.ReferencedTable = ku.TABLE_NAME
)
select *
from CTE_ALL
where CTE_ALL.ReferencingTable = 'my table name'
它错误地给出以下消息
Msg 530, Level 16, State 1, Line 1
The statement terminated. The maximum recursion 100 has been exhausted before
statement completion.
这显然意味着我的查询被计划用尽所有 SQL 资源。Microsoft 的尽职调查可以防止这种情况发生。我想知道我是否可以在没有while循环的情况下使用单个查询并且没有临时表来做到这一点。
我知道我的根表名称和我的根列 id,我也知道我的叶节点表名称,虽然我不能说什么可能是叶节点列名称
我必须找到这个,因为我正在运行时设计一个查询并执行它。此查询需要在运行时构造 ON 子句之间的内部连接。不确定我是否有意义。