2012-08-09 16 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