如何计算表连接中的行数?

时间:2013-01-18 20:23:46

标签: sql sql-server

我正在开发一个SQL sproc,我想返回每个表的行数。我怎么能重写这个语句,以便列出下面每个表中的行数?

SELECT COUNT(*)
FROM [test_setup_details_form_view] [tsdf]
JOIN [test_setup_header_form_view] 
    ON [test_setup_header_form_view].[test_setup_header_id] 
        = [tsdf].[test_setup_header_id]
JOIN [test_header_rv] [th] with(nolock) 
    ON [th].[test_setup_header_id] 
        = [test_setup_header_form_view].[test_setup_header_id]
JOIN [test_details_answers_expanded_view] [tdae] 
    ON [tdae].[test_setup_details_id] = [tsdf].[test_setup_details_id] 
        AND [th].[test_header_id] = [tdae].[test_header_id]
JOIN [event_log_rv] [e] 
    ON [e].[event_log_id] = [tdae].[event_log_id]

当我执行这个语句时,它只是给了我所有连接后的总行数。

3 个答案:

答案 0 :(得分:3)

如果您试图获取每个表的计数而不管连接如何:

SELECT
  OBJECT_SCHEMA_NAME([object_id]),
  OBJECT_NAME([object_id]),
  c
FROM
( 
  SELECT [object_id],
    c = SUM(row_count)
  FROM
    sys.dm_db_partition_stats -- no NOLOCK necessary
  WHERE
    index_id IN (0,1)
    AND OBJECT_NAME([object_id]) IN
    ( 
      N'test_setup_details_from_view',
      N'test_setup_header_from_view',
      ... etc etc. ...
    )
  GROUP BY [object_id]
) AS x;

答案 1 :(得分:1)

对每个需要计算的表的唯一列使用count (distinct <columnname>)

答案 2 :(得分:-2)

从每张桌子?那么为什么不使用元数据表呢?

您正尝试在元数据表中已存在的代码中执行某些操作:

Select 
    schema_name(schema_id) + '.' + t.name as TableName
,   i.rows
from sys.tables t (nolock) 
    join sys.sysindexes i (nolock) on t.object_id = i.id 
        and i.indid < 2