我想在一個存儲過程中獲得此查詢的結果。與此查詢我想在table1
返回的行數table4
選擇不同表中的記錄數
select count(*) from table1
select count(*) from table2
select count(*) from table3
select count(*) from table4
我想有這樣的結果在一個臨時表,並選擇臨時表中的所有列。
我想在一個存儲過程中獲得此查詢的結果。與此查詢我想在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
如何可以創建臨時表並填寫此計數(*)在臨時列 – Moslem7026
爲什麼你會這樣做,這個查詢給出結果如表(table_name,record_count) – S3ddi9
要創建臨時表,只需在「創建臨時表temp_table_name」行之前選擇語句。這將使用SELECT語句的結果創建一個臨時表。 – Tom
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();
}
假設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
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
再次,這不是一個優雅的解決方案。
爲什麼它不是優雅的解決方案? – Moslem7026
我會說這不是優雅的,因爲你必須硬編碼查詢中的所有表名。但它完成了工作。 – Tom
可能你應該刪除** c#標記**,如果你想要一個sql存儲過程 – S3ddi9