列出每个视图和表的行数

时间:2016-06-02 02:38:02

标签: sql-server dynamic-sql information-schema

我有一个名为test的数据库,它有2个视图和2个模式dbo中的表,如下所示: example database

我想创建一个名为report的表,其中列出了每个视图和每个表的行号。这个概念是这样的:

select table_name, table_type, "select count(*) from table_name" as rowCount
into test.dbo.report
from test.INFORMATION_SCHEMA.tables;

test.dbo.report应如下所示:

enter image description here

但是,我不知道如何实施。动态SQL可能是要走的路,但有些令人困惑。

我正在使用SQL Server 2014。

3 个答案:

答案 0 :(得分:4)

由于您专门使用SQL Server,因此您不必人为地限制自己使用信息架构。您需要的信息位于动态管理视图中。或者,一个具体的观点:

select object_name(object_id), sum(rows) 
from sys.partitions
where index_id in (0, 1)
group by object_id;

行数是近似值,但根据我的经验,它通常非常接近。您确实可以不必扫描每个表的数据来获取计数。注意:除非视图是索引视图,否则这对视图不起作用。

答案 1 :(得分:3)

您可以使用动态SQL构建一个巨大的union all select语句链:

declare @sql nvarchar(max) = ''

-- use an undocumented(?) trick with string concatenation in a select statement
select @sql = @sql + 'union all select ' + 
    '''' + TABLE_NAME + ''' as TABLE_NAME, ' + 
    '''' + TABLE_TYPE + ''' as TABLE_TYPE, ' + 
    '(select count(*) from ' + TABLE_NAME + ') as [COUNT]' + 
    char(13) + char(10) 
from INFORMATION_SCHEMA.TABLES

-- remove leading "union all"
set @sql = right(@sql, len(@sql)-len('union all '))

--print @sql    -- to check what's going to be executed

exec sp_executesql @sql

它构建和执行的SQL如下所示:

select 'customers' as TABLE_NAME, 'BASE TABLE' as TABLE_TYPE, (select count(*) from customers) as [rowcount]
union all select 'items' as TABLE_NAME, 'BASE TABLE' as TABLE_TYPE, (select count(*) from items) as [rowcount]
union all select 'orders' as TABLE_NAME, 'VIEW' as TABLE_TYPE, (select count(*) from orders) as [rowcount]
union all ...

不幸的是,你不能将动态SQL作为select语句中的列执行 - 没有任何东西可以让你做任何简单的事情:

select table_name, table_type, exec('select count(*) from ' + table_name) as [count]
into test.dbo.report --         /\== doesn't work
from test.INFORMATION_SCHEMA.tables;

答案 2 :(得分:1)

运行以下查询

    DECLARE     @SQL VARCHAR(MAX);
    SET         @SQL = '';

    SELECT @SQL = @SQL + 'INSERT INTO test.dbo.report SELECT ''' +
                 TABLE_SCHEMA + '.' + table_name +  ''', ''' + table_type + ''', COUNT(*) FROM ' +
                 TABLE_SCHEMA + '.' + table_name +
                 CHAR(13)  from INFORMATION_SCHEMA.tables

    EXEC (@SQL)