查找特定列不存在的表 sql 服务器
Find tables for which specific column not exists sql server
如何查找 table 中不存在特定列的内容。
例如,列 ID
不存在于 table Contact
中,那么 Contact
table 将出现在结果集中。
我试过了:
SELECT DISTINCT t.name
FROM sys.tables t
INNER join sys.columns C ON c.object_id = t.object_id
WHERE c.name <> 'ID'
但上面的查询 return all table 其中存在列 ID
。
你能试试这个查询吗,
SELECT * FROM sys.tables WHERE type = 'U' AND object_id NOT IN (
SELECT DISTINCT c.object_id FROM sys.columns c WHERE c.name = 'ID')
SELECT name
FROM sys.Tables
WHERE Object_ID NOT IN (SELECT Object_ID FROM sys.Columns WHERE name = 'ID')
您不需要执行连接,您只需添加一个子查询来标识具有 ID 列的 table 并使用 NOT IN(..the subquery..)
排除 object_id :
SELECT DISTINCT t.name
FROM sys.tables t
WHERE t.object_id NOT IN (SELECT object_id FROM sys.columns WHERE name = 'id')
您的查询不起作用的原因是因为您只是获取所有不等于 ID
的列,并且每个 table 都有许多符合该条件的列,因此它们将被返回即使有 ID
列。
一种方法是 NOT EXISTS:
SELECT OBJECT_SCHEMA_NAME(t.object_id) AS SchemaName
, t.name AS TableName
FROM sys.tables t
WHERE NOT EXISTS ( SELECT *
FROM sys.columns c
WHERE c.object_id = t.object_id
AND c.name = 'ID' );
尝试以下操作,列出所有 table 个没有 ID 的名称。
SELECT tableName
FROM (
SELECT DISTINCT
t.name AS tableName
,c.name AS columnName
FROM sys.tables t
INNER JOIN sys.columns C
ON c.object_id = t.object_id
) AS t
WHERE columnName NOT IN( 'ID')
GROUP BY tableName
如果您不想看到系统表,那么..
SELECT DISTINCT OBJECT_NAME(OBJECT_ID) TableName FROM SYS.COLUMNS WHERE NAME <> 'id'
and OBJECTPROPERTY (OBJECT_ID, 'IsUserTable') = 1
EXCEPT
SELECT DISTINCT OBJECT_NAME(OBJECT_ID) TableName FROM SYS.COLUMNS WHERE NAME = 'id'
如何查找 table 中不存在特定列的内容。
例如,列 ID
不存在于 table Contact
中,那么 Contact
table 将出现在结果集中。
我试过了:
SELECT DISTINCT t.name
FROM sys.tables t
INNER join sys.columns C ON c.object_id = t.object_id
WHERE c.name <> 'ID'
但上面的查询 return all table 其中存在列 ID
。
你能试试这个查询吗,
SELECT * FROM sys.tables WHERE type = 'U' AND object_id NOT IN (
SELECT DISTINCT c.object_id FROM sys.columns c WHERE c.name = 'ID')
SELECT name
FROM sys.Tables
WHERE Object_ID NOT IN (SELECT Object_ID FROM sys.Columns WHERE name = 'ID')
您不需要执行连接,您只需添加一个子查询来标识具有 ID 列的 table 并使用 NOT IN(..the subquery..)
排除 object_id :
SELECT DISTINCT t.name
FROM sys.tables t
WHERE t.object_id NOT IN (SELECT object_id FROM sys.columns WHERE name = 'id')
您的查询不起作用的原因是因为您只是获取所有不等于 ID
的列,并且每个 table 都有许多符合该条件的列,因此它们将被返回即使有 ID
列。
一种方法是 NOT EXISTS:
SELECT OBJECT_SCHEMA_NAME(t.object_id) AS SchemaName
, t.name AS TableName
FROM sys.tables t
WHERE NOT EXISTS ( SELECT *
FROM sys.columns c
WHERE c.object_id = t.object_id
AND c.name = 'ID' );
尝试以下操作,列出所有 table 个没有 ID 的名称。
SELECT tableName
FROM (
SELECT DISTINCT
t.name AS tableName
,c.name AS columnName
FROM sys.tables t
INNER JOIN sys.columns C
ON c.object_id = t.object_id
) AS t
WHERE columnName NOT IN( 'ID')
GROUP BY tableName
如果您不想看到系统表,那么..
SELECT DISTINCT OBJECT_NAME(OBJECT_ID) TableName FROM SYS.COLUMNS WHERE NAME <> 'id'
and OBJECTPROPERTY (OBJECT_ID, 'IsUserTable') = 1
EXCEPT
SELECT DISTINCT OBJECT_NAME(OBJECT_ID) TableName FROM SYS.COLUMNS WHERE NAME = 'id'