SQL列存在且不存在

时间:2017-06-09 16:08:15

标签: sql sql-server-2008

在我的数据库测试中,我有400个表。我想知道列ID存在于哪个表中,以及列ID不存在于哪些表中。 (见图)

enter image description here

我尝试使用此查询,但无法正常工作。什么是最好的方式?

 SELECT COLUMNS.TABLE_NAME, 'Yes' As MyCol_ID
 FROM   INFORMATION_SCHEMA.COLUMNS COLUMNS,
   INFORMATION_SCHEMA.TABLES TABLES
 WHERE  COLUMNS.TABLE_NAME = TABLES.TABLE_NAME
   AND Upper(COLUMNS.COLUMN_NAME) = Upper('ID') 
   AND  TABLES.TABLE_TYPE='BASE TABLE'
   order by COLUMNS.TABLE_NAME

 UNION 

SELECT COLUMNS.TABLE_NAME, 'No' As MyCol_ID
 FROM   INFORMATION_SCHEMA.COLUMNS COLUMNS,
   INFORMATION_SCHEMA.TABLES TABLES
 WHERE  COLUMNS.TABLE_NAME = TABLES.TABLE_NAME
   AND Upper(COLUMNS.COLUMN_NAME) <> Upper('ID') 
   AND  TABLES.TABLE_TYPE='BASE TABLE'
   order by COLUMNS.TABLE_NAME

2 个答案:

答案 0 :(得分:2)

一种方法基本上是left join

select t.table_schema, t.table_name,
       (case when c.column_name is null then 'no' else 'yes' end) as id_exists
from information_schema.tables t left join
     information_schema.columns c
     on t.table_name = c.table_name and t.table_schema = c.table_schema and
        c.column_name = 'ID' 
where t.table_type = 'BASE_TABLE';

请注意,我修复了连接以包含模式名称和表名。

答案 1 :(得分:1)

我喜欢使用sys.变体。在测试数据库的上下文中运行它:

SELECT T.NAME, CASE WHEN C.NAME = 'my_ColID' THEN 'YES' ELSE 'NO' END
FROM SYS.TABLES T
LEFT JOIN SYS.COLUMNS C ON C.object_id = T.object_id 
                       AND C.NAME = 'my_ColID'
ORDER BY T.NAME