0

このクエリの結果を1つのストアドプロシージャにまとめたいと思います。このクエリでは、行数をに返しtable1たいtable4

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
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 に答える
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 に答える
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

dm_db_partition_statsSQL Serverを想定すると、行数をすばやく取得するための信頼できる方法であることがわかりました。

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 に答える