选择各种表中的记录数

时间:2012-09-17 16:17:05

标签: sql tsql stored-procedures

我希望在一个存储过程中获得此查询的结果。使用此查询,我想将table1中的行数返回到table4

select count(*) from table1
select count(*) from table2
select count(*) from table3
select count(*) from table4

我希望将此结果放在临时表中并选择临时表的所有列。

5 个答案:

答案 0 :(得分:5)

这是一个不太优雅的解决方案:

SELECT  'table1' as table_name, COUNT(*) as record_count from table1
UNION ALL 
SELECT  'table2' as table_name, COUNT(*) as record_count from table2
UNION ALL 
SELECT  'table3' as table_name, COUNT(*) as record_count from table3
UNION ALL 
SELECT  'table4' as table_name, COUNT(*) as record_count from table4

答案 1 :(得分:1)

INSERT INTO #temp
SELECT * FROM 
(

    select Cnt = count(*) from table1 Union All
    select count(*) from table2 Union All
    select count(*) from table3 Union All
    select count(*) from table4
)X

DROP TABLE #temp

答案 2 :(得分:1)

要在单个记录中执行此操作,您可以执行以下操作:

SELECT  (SELECT COUNT(*) from table1) table1_rec_count,
        (SELECT COUNT(*) from table2) table2_rec_count,
        (SELECT COUNT(*) from table3) table3_rec_count,
        (SELECT COUNT(*) from table4) table4_rec_count

同样,这不是一个优雅的解决方案。

答案 3 :(得分:0)

    myCommand.CommandType = CommandType.StoredProcedure;
    myCommand.Connection = myConnection;
    myCommand.CommandText = "MyProc";

    try
    {
        myConnection.Open();

        myReader = myCommand.ExecuteReader();    
        while (myReader.Read())
        {
                //Write logic to process data for the first result.
        }

        myReader.NextResult();
        while (myReader.Read())
        {
                //Write logic to process data for the second result.
        }
    }
    catch(Exception ex) 
    {
        // catch exceptions
    }
    finally
    {
        myConnection.Close();
    }

答案 4 :(得分:0)

假设SQL Server,我发现dm_db_partition_stats是一种快速获取行数的可靠方法:

SELECT [TableName] = '[' + s.name +'].[' + t.name + ']'
, [RowCount] = SUM(p.row_count)OVER(PARTITION BY t.object_id)
FROM sys.tables t
JOIN sys.schemas s ON s.schema_id = t.schema_id
JOIN sys.dm_db_partition_stats p ON p.object_id = t.object_id
WHERE t.[type] = 'U'
AND p.index_id IN (0,1)
AND t.name IN ('table1','table2','table3','table4') --Just table names here, but it's best practice to also include schemas
ORDER BY s.name, t.name