我有一个名为
test
的数据库,其中包含架构 dbo
下的 2 个视图和 2 个表:
我想创建一个名为
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
) 应如下所示:
我仍在尝试使用动态 SQL,但到目前为止还没有运气。
我正在使用 SQL Server 2014。
由于您专门使用 SQL Server,因此您不必人为地限制自己使用信息模式。您需要的信息位于动态管理视图中。或者,具体一种观点:
select object_name(object_id), sum(rows)
from sys.partitions
where index_id in (0, 1)
group by object_id;
行数是近似值,但根据我的经验,它通常非常接近。您确实有一个好处,即不必仅仅为了获得计数而扫描每个表的数据。注意:除非视图是索引视图,否则这不适用于视图。
您可以使用动态 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)