このクエリの結果を1つのストアドプロシージャにまとめたいと思います。このクエリでは、行数をに返しtable1
たいtable4
select count(*) from table1
select count(*) from table2
select count(*) from table3
select count(*) from table4
この結果を一時テーブルに入れて、一時テーブルのすべての列を選択したいと思います。
このクエリの結果を1つのストアドプロシージャにまとめたいと思います。このクエリでは、行数をに返しtable1
たいtable4
select count(*) from table1
select count(*) from table2
select count(*) from table3
select count(*) from table4
この結果を一時テーブルに入れて、一時テーブルのすべての列を選択したいと思います。
これはあまりエレガントではない解決策です:
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
これを単一のレコードで行うには、次のようにします。
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
繰り返しますが、これは洗練されたソリューションではありません。
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();
}
dm_db_partition_stats
SQL 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