SQL - 从公共列为空的所有表中获取行

时间:2015-12-08 21:41:34

标签: sql sql-server information-schema

我需要找到创建/更新日期为空的任何表中的所有行

有超过500个表,所以做以下事情是不可行的。

SELECT * 
FROM 
    (SELECT 
         'tableA' AS `table`,
         IF(COUNT(`column_a`), NULL, 'column_a') AS `column`
     FROM tableA

     UNION ALL

     SELECT 
         'tableB' AS `table`,
         IF(COUNT(`column_b`), NULL, 'column_b') AS `column`
     FROM tableB

     UNION ALL
     -- etc.
     ) t 
WHERE 
    `column` IS NOT NULL

我想我可能会以某种方式使用INFORMATION_SCHEMA,但我对此感到困难。

1 个答案:

答案 0 :(得分:0)

我通常使用sys.tables将表的列表填充到临时表中,然后围绕该列表组成动态SQL。

select quotename( schemas.name ) + '.' + quotename(tables.name) as tbl
into #work 
from sys.tables
join sys.schemas on tables.schema_id = schemas.schema_id

select 

'select ''' + tbl + ''' as [table] where exists ( select * from ' + tbl + ' where column_a is null )' as sqlcmd,

'select ''' + tbl + ''' as [table], * from ' + tbl + ' where createdate is null ' as sqlcmd

from #work

drop table #work

获得列表后,您可以在SSMS中手动执行它,或者使用游标迭代它以执行每个语句。但引号会让你头疼。动态SQL并不适合胆小的人。