选择没有依赖项的SQL表名

时间:2016-03-29 11:43:29

标签: sql sql-server

我见过可以显示SQL表依赖关系的脚本,但是没有可以选择没有依赖关系的表的表名的脚本。

理想情况下,我想选择所有以Q开头的表名(如下所示),并且在MSSQL中没有依赖关系,即

SELECT t.NAME AS TableName
FROM sys.Tables t
where t.Name LIKE 'Q%' and no dependencies!

2 个答案:

答案 0 :(得分:2)

你应该在sys.sql_expression_dependencies上保持联接并抓住没有被引用的表格,例如:

SELECT t.NAME AS TableName
     FROM sys.Tables t
LEFT JOIN sys.sql_expression_dependencies d ON d.referenced_id = t.object_id
    WHERE t.Name LIKE 'Q%'
      AND d.referenced_id IS NULL

答案 1 :(得分:1)

这个怎么样:

select * from INFORMATION_SCHEMA.TABLES T
where T.TABLE_NAME like 'Q%'
and not exists (
    select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
    where TC.TABLE_NAME      = T.TABLE_NAME
    and   TC.CONSTRAINT_TYPE = 'FOREIGN KEY'   -- add conditions as needed
)
order by TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME