如何搜索未连接的表

时间:2017-05-26 05:56:33

标签: sql-server foreign-keys

如何获取所有未连接表的表名(未使用外键连接到另一个表)。使用SQL Server?

下面是表格结构。该查询应仅返回Table4,因为它未使用任何约束连接到任何表。

表格结构:Click here

2 个答案:

答案 0 :(得分:0)

查询查找哪些表没有定义任何外键(但可能被其他键引用):

    select t.[name] from sys.tables t
    left join sys.foreign_keys k on t.object_id = k.parent_object_id
    where k.object_id is null

查询以查找未被任何键引用的表:

select t.[name] from sys.tables t
left join sys.foreign_keys k on t.object_id = k.referenced_object_id
where k.object_id is null

答案 1 :(得分:0)

没有外键的表:

SELECT [name] FROM sys.objects 
WHERE [type] = 'U' AND object_id NOT IN (
    SELECT f.parent_object_id
    FROM sys.foreign_keys AS f 
    INNER JOIN sys.foreign_key_columns AS fc 
       ON f.OBJECT_ID = fc.constraint_object_id )