[英]Two SELECTS, One query
我想從數據庫的兩個表中提取信息。 A的一行,B的行帶有FK到我從A拉出的行。
我想使用兩個select語句使它成為單個存儲的proc,而不必對數據庫進行兩次調用。
我知道幾種從單個選擇中提取信息的方法...但是不記得如何從多個選擇中獲取數據。 谷歌搜索已被證明很困難,因為我在想出名詞/動詞來描述無法描述一百萬種其他事物的情況時遇到了麻煩。
有人可以指出我正確的方向嗎?
(為簡單起見,我知道使用“ using”語句,等等……我只需要該方法的基本思想即可)。
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand com = new SqlCommand(commandString, conn))
{
<somehow get multiple select's of data here in one call>
}
}
如果您習慣使用SqlDataReader,則只需要讓存儲過程或sql語句執行多次選擇並調用NextResult()
即可移至下一個結果集:
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(commandString, conn);
// Add parameters here
using (SqlDataReader reader = cmd.ExecuteReader())
{
// This will read the first result set
while(reader.Read())
{
// Read data
}
// This will read the second result set
if (!reader.NextResult())
{
throw new ApplicationException("Only one result set returned");
}
while (reader.Read())
{
// Read data
}
}
}
如果您習慣於使用數據適配器返回數據表,那么您要做的就是讓數據適配器填充數據集並從Tables屬性中提取結果集:
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(commandString, conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable firstResult = ds.Tables[0];
DataTable secondResult = ds.Tables[1];
}
var reader = com.ExecuteReader();
while(reader.Read())
{
//do operations for the first select here
}
reader.NextResult();
while(reader.Read())
{
//do operations for the second select here
}
注意:可能存在語法錯誤,未檢查。 但是重點是,使用SqlDataReader.NextResult()。
您需要使用MARS ,它允許您從多個選擇中加載DataTable作為一個DataTableCollection。
也許我誤會了您要做什么,但是您不能使用聯接和數據讀取器來獲取此信息嗎?
大致(在命令的using語句中)
select a.foo, b.bar from a, b where a.id = 2 and b.foo = a.foo;
using( DbDataReader reader = com.executeReader() )
{
while( reader.read() )
{
myA.foo = reader[0].toString();
myB.bar = reader[1].toString();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.