简体   繁体   English

选择各种表中的记录数

[英]Select number of records in various tables

I want to have the result of this queries in one stored procedure. 我想在一个存储过程中获得此查询的结果。 With this query I want to return the number of rows in table1 to table4 通过此查询,我想将table1的行数返回到table4

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

I want to have this result in a temp table and select all columns of temp table. 我想在临时表中得到此结果,然后选择临时表的所有列。

Here's a not very elegant solution: 这不是一个非常优雅的解决方案:

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
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

To do this in a single record, you could do this: 要在单个记录中执行此操作,可以执行以下操作:

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

Again, this is not an elegant solution. 同样,这不是一个很好的解决方案。

    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();
    }

Assuming SQL Server, I have found dm_db_partition_stats to be a reliable way to get the row counts quickly: 假设使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM