列出每个视图的行数和 table

List row count of each view and table

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

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

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

test.dbo.report 应该是这样的:

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

我正在使用 SQL Server 2014。

您可以使用动态 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;

运行 下面查询

    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)

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

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

行数是近似值,但根据我的经验,它通常非常接近。您确实受益于不必扫描每个 table 的数据就可以得到一个计数。注意:这不适用于视图,除非视图是索引视图。