0

我想在一个存储过程中得到这个查询的结果。使用此查询,我想将行数返回table1table4

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

我想在临时表中得到这个结果并选择临时表的所有列。

4

5 回答 5

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
于 2012-09-17T16:19:58.670 回答
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

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

于 2012-09-19T13:48:47.667 回答
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
于 2012-09-18T03:41:00.677 回答
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();
    }
于 2012-09-17T16:21:38.727 回答
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
于 2012-09-17T17:27:31.837 回答