sql—获取表不为空的数据库中的所有外键关系

xkrw2x1b  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(301)

我正在尝试改进这个query.link
但是系统抱怨“tp”(无效的对象名“tp”)
有没有办法从有行(不是空的)的表中获取外键。

SELECT
    fk.name 'FK Name',
    tp.name 'Parent table',
    cp.name, cp.column_id,
    tr.name 'Refrenced table',
    cr.name, cr.column_id
FROM 
    sys.foreign_keys fk
INNER JOIN 
    sys.tables tp ON fk.parent_object_id = tp.object_id
INNER JOIN 
    sys.tables tr ON fk.referenced_object_id = tr.object_id
INNER JOIN 
    sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN 
    sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id
INNER JOIN 
    sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id
    where (SELECT COUNT(*) FROM tp)>0 --HERE IS THE PROBLEM WITH tp
ORDER BY

    tp.name, cp.column_id
2ledvvac

2ledvvac1#

使用 EXISTS 用于标识非空表的相关子查询。下面是一个使用 sys.partitions .

SELECT
    fk.name 'FK Name',
    tp.name 'Parent table',
    cp.name, cp.column_id,
    tr.name 'Refrenced table',
    cr.name, cr.column_id
FROM 
    sys.foreign_keys fk
INNER JOIN 
    sys.tables tp ON fk.parent_object_id = tp.object_id
INNER JOIN 
    sys.tables tr ON fk.referenced_object_id = tr.object_id
INNER JOIN 
    sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN 
    sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id
INNER JOIN 
    sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id
WHERE EXISTS(SELECT 1 FROM sys.partitions as p WHERE tp.object_id = p.object_id AND p.index_id IN(0,1) AND p.rows > 0)
ORDER BY
    tp.name, cp.column_id;

相关问题