我想输出为从名称为“ T_”的数据库获取所有表。 我写了查询,它获取所有表名。 但我不希望将查询作为“从数据库联合中的所有表中选择count(*)”
表示我想获得
select count(*) from T1 UNION
select count(*) from T2 UNION
select count(*) from T3 UNION...
,依此类推 有1000行,所以我想要一个查询,查询本身将输出count(*)查询。
select 'select count(*) from ' + table_name from INFORMATION_SCHEMA.TABLES where table_type='BASE TABLE'
and left(table_name,2) = 'T_'
order by TABLE_NAME
此查询给出所有select count(*) table names like T_*
select 'select count(*) from ' + table_name from INFORMATION_SCHEMA.TABLES where table_type='BASE TABLE'
and left(table_name,2) = 'T_'
order by TABLE_NAME
+'UNION';
获取输出
select count(*) from T_T1
select count(*) from T_T2
select count(*) from T_T3
预期产量
select count(*) from T_T1 UNION
select count(*) from T_T2 UNION
select count(*) from T_T3 UNION
答案 0 :(得分:2)
order by TABLE_NAME + ' UNION'
表示您想按TABLE_NAME
的值排序,并将其与字符串UNION
串联在一起(不会改变任何内容)
您需要在您的UNION
:UNION ALL
中放入SELECT
(实际上我在这里建议...table_type='BASE TABLE' + N' UNION ALL '
。)
我还建议将table_name
更改为QUOTENAME(table_name)
。向您提供以下最终查询:
SELECT N'SELECT COUNT(*) FROM' + QUOTENAME(TABLE_NAME) + NCHAR(13) + NCHAR(10) + N'UNION ALL'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND LEFT(TABLE_NAME, 2) = 'T_'
ORDER BY TABLE_NAME;
答案 1 :(得分:1)
select 'select count(*) from ' + table_name + ' UNION ' from INFORMATION_SCHEMA ...