表:
Col
------
Table1
table2
table3
查询:
select count(*)
from @tablename
我想将table1
,table2
,table3
作为@tablename
的参数传递给select查询并获取每个表的计数
期望的输出:
2 (table 1 count) 3 (table 2 count) 4 (table 3 count)
答案 0 :(得分:1)
您可以使用动态sql和游标来运行它们:
创建用于测试的临时表:
DECLARE @tablenametable TABLE(tablename VARCHAR(100));
INSERT INTO @tablenametable
VALUES('table1'), ('table2'), ('table3');
使用游标运行表
中的所有表名DECLARE @tablename VARCHAR(100);
DECLARE dbcursor CURSOR
FOR
SELECT tablename
FROM @tablenametable;
OPEN dbcursor;
FETCH NEXT FROM dbcursor INTO @tablename;
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @sql VARCHAR(MAX);
SET @sql = 'select count(*) from '+@tablename;
PRINT(@sql);
FETCH NEXT FROM dbcursor INTO @tablename;
END;
CLOSE dbcursor;
DEALLOCATE dbcursor;
给出以下结果:
select count(*) from table1
select count(*) from table2
select count(*) from table3
当您对此感到满意时,只需将PRINT(@SQL)
更改为EXEC(@SQL)
答案 1 :(得分:0)
您可以使用动态SQL查询。
<强>查询强>
declare @sql as varchar(max);
select @sql = stuff((
select ' union all '
+ 'select cast(count(*) as varchar(100))
+ ' + char(39) + '(' + [Col] +' Count)' + char(39)
+ ' as [table_counts] '
+ ' from ' + [col]
from [your_table_name]
for xml path('')
)
, 1, 11, ''
);
exec(@sql);
Find a demo here
强> 答案 2 :(得分:0)
如前所述,您必须使用动态SQL。
第一种方法是自己指定表名:
declare @tablename varchar(30), @SQL varchar(30)
set @tablename = 'Table1' --here you specify the name
set @SQL = concat('SELECT COUNT(*) FROM ', @tablename) --here you build the query
EXEC(@SQL)
第二种方法允许您使用具有表名称的表:
declare @SQL varchar(8000)
set @SQL = ''
declare @TableNames table(name varchar(30))
insert into @TableNames values ('Table1'), ('Table2'), ('Table3')
--here you build the query
select @SQL = @SQL + ' SELECT ''' + name + ''' AS [TableName], COUNT(*) AS [Count] FROM ' + name + ' UNION ALL' from @TableNames
-- get rid of last "UNION ALL"
set @SQL = LEFT(@SQL, LEN(@SQL) - 10)
--execute the query
EXEC(@SQL)
结果将是:
TableName Count
Table1 3
Table2 6
Table3 4
答案 3 :(得分:0)
您可以像{sup> [1] 一样使用sys.dm_db_partition_stats
:
select
t.col tableName, sum(s.row_count) tableCount
from
yourTable t
join
sys.dm_db_partition_stats s
on
(object_name(s.object_id) = t.col )
and
(s.index_id < 2)
group by
t.col;
一行输出版本为:
select
sum(s.row_count), ' ('+t.col +' count) '
from
yourTable t
join
sys.dm_db_partition_stats s
on
(object_name(s.object_id) = t.col )
and
(s.index_id < 2)
group by
t.col
for xml path('');
输出:
2 (Table1 count) 3 (table2 count) 4 (table3 count)