在SQL Server中获取列名,行数和表名

问题描述 投票:0回答:1

我有一个条件,其中我的表包含一列,该列具有5行。这5行是表名,我需要执行这些表名才能获得无行。

此外,我需要在这5个表中的每个表中检索1列值。

ex:

 Table name: PHP     
    'select all_tables from kbc'
o/p: all_tables
     Customers
     Hr
     PHP
     xyz
     abc

我有客户,HR,Php,xyz,abc表。假设这些表有一些行。另外,我需要在这5个表中的每个表中选择company_code列。

预期结果应该是:

 table_name rowcount Company_code
    Customers     10     123
    Hr            20     234
    PHP           50     345
    XYZ           100     456
    abc           05     567

我得到了table_name并通过对我们的标准查询使用sys.objectssys.partitions进行计数。

sql sql-server sql-server-2012
1个回答
0
投票

如果没有太多的表列表,则可以使用游标来实现

select * into #kbc from (
    select 'Customers' table_name 
    union all
    select 'Hr' table_name 
    union all
    select 'PHP' table_name 
    union all
    select 'xyz' table_name 
    union all
    select 'abc' table_name 
)#kbc

declare @tableCursor cursor,
        @tableName varchar(100)

declare @sql nvarchar(max)
set @sql = '';
set @tableCursor = cursor for select table_name from #kbc

open @tableCursor
fetch next from @tableCursor into @tableName
while(@@fetch_status = 0)
begin     
    set @sql = @sql +'select '''+@tableName+''' as table_name, count(1) as [rowcount], company_code from '+@tableName + ' union all '

    fetch next from @tableCursor into @tableName
end
set @sql = left(@sql, len(@sql) - len(' union all '));
print @sql;
exec sp_executesql @sql
close @tableCursor
deallocate @tableCursor
drop table #kbc

将产生print @sql

select 'Customers' as table_name, count(1) as [rowcount], company_code from Customers 
union all 
select 'Hr', count(1) as [rowcount], company_code from Hr 
union all 
select 'PHP', count(1) as [rowcount] , company_code from PHP 
union all 
select 'xyz', count(1) as [rowcount] , company_code from xyz 
union all 
select 'abc', count(1) as [rowcount] , company_code from abc
© www.soinside.com 2019 - 2024. All rights reserved.