如何获取各种表中使用的所有列?

时间:2015-05-05 23:06:58

标签: mysql sql-server stored-procedures

假设我有10个表(Table1 - Table10),每个表中有10列(比如Column1 - Column10) - 表中的列名相同。我想在所有表中找到not NULL的所有列,该表中至少有一行,并将它们插入到临时表中,例如@usedColumns,稍后将在存储过程中使用。

假设您在任何或所有这些表中都有数百万条记录,那么最快,最有效的方法是什么?当前的实现使用UNPIVOT,但我试图重新设计该存储过程,因为它的表现非常慢。或者UNPIVOT真的是最有效的方式吗?

我想的一种方法是只检查if exists,但无法弄清楚如何将其置于有效的循环中:

if exists (select top 1 1
    from Table1
    where Column1 is not null)
    insert into @usedColumns ( table_name, column_name )
    values                   ( 'Table1',   'Column1'   );

if exists (select top 1 1
    from Table1
    where Column2 is not null)
    insert into @usedColumns ( table_name, column_name )
    values                   ( 'Table1',   'Column2'   );
...

有问题的数据库是SQL Server,但我猜这个解决方案也适用于MySQL和其他人。

1 个答案:

答案 0 :(得分:0)

我会这样做。对不起,我正在用手机打字。

declare @sql nvarchar(max)
declare @count int = 1
declare @tablename nvarchar(20)

while @count < 11
begin    
    select @tablename = concat('table', @count)    
    select @sql = concat('select * from '
                    , @tablename
                    , ' where column1 is not null...')    
    --select @sql
    exec sp_sqlexec @sql    
    select @count = @count + 1    
end
相关问题