2012-08-09 73 views
0

我有15个表,它们都有列CreationDate和LastModifiedDate有一种方法来查询所有表,并在表中查找空值。SQL查询与同一列的多个表

这就是我想我必须做的,但不知道是否有更有效的方法或更简单的方法做以下

Select COUNT(*) FROM Table1, Table2, Table3 
WHERE table1.CreationDate IS NULL 
     OR table1.LastModifiedDate IS NULL 
     OR table2.CreationDate IS NULL 
     OR table2.LastModifiedDate IS NULL 
     OR table3.CreationDate IS NULL 
     OR table3.LastModifiedDate IS NULL 

回答

3
select count(*) 
from (
    select CreationDate, LastModifiedDate from Table1 
    union all 
    select CreationDate, LastModifiedDate from Table2 
    union all 
    select CreationDate, LastModifiedDate from Table3 
) a 
where CreationDate is null or LastModifiedDate is null 
+0

非常聪明 - +1上一个! – 2012-08-09 15:47:09

+0

非常感谢 – 2012-08-09 15:55:49

+0

会有一种简单的方法来更新那些GETDATE()为null的时间吗? – 2012-08-09 17:57:55

0

您最初的查询不会做你期待什么。它在所有缺少值的行中进行交叉连接。这会导致大量数据(如果所有表都有多行)或根本没有(如果没有缺失行)。

我假设你想知道的表名里的东西丢失:

select tablename, count(*), 
     sum(case when CreationDate is null then 1 else 0 end) as MissingCreationDate, 
     sum(case when LastModifiedDate is null then 1 else 0 end) as MissingLastModifiedDate 
from ((select 'table1' as tablename, CreationDate, LastModifiedDate 
     from Table1 
    ) union all 
     (select 'table2' as tablename, CreationDate, LastModifiedDate 
     from Table2 
    ) union all 
     . . . 
     (select 'table15', CreationDate, LastModifiedDate 
     from Table3 
    ) 
    ) t 
where CreationDate is null or LastModifiedDate is null 
group by tablename