2009-07-02 77 views
2

我想從數據庫的兩個表中拉下信息。從A的一行和B的FK到行I從A中拉出的行。兩個選擇,一個查詢

我想使用兩個select語句將其作爲單個存儲過程,而不是必須對D B。

我知道從單個選擇中提取信息的幾種方法......但不記得如何從多個選擇中獲取數據。谷歌搜索已被證明是困難的,因爲我很難找出名詞/動詞來描述沒有描述其他事情的情況。

有人能指出我正確的方向嗎? (爲了保持簡單,我知道使用「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> 
    } 
} 

回答

4

如果你習慣使用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 
     } 
    } 
} 

如果你習慣使用數據適配器返回數據表,那麼所有你需要做的是有你的數據適配器填充數據集,並從表屬性提取結果集:

​​
0

您需要使用M.A.R.S,它允許您從多個選擇加載數據表作爲一個DataTableCollection中。

+1

原始文章中沒有任何內容表示需要同時使用多個結果集。 – 2009-07-02 18:20:59

3
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()。

+0

這看起來正是我所需要的......但我似乎沒有看到.ReadNext()方法......我是否缺少拉我需要的庫? – Beska 2009-07-02 18:15:04

+0

@Beska:NextResult,而不是ReadNext。我只是更新了代碼。 – 2009-07-02 18:16:32

0

也許我誤解了你正在嘗試做的事情,但是你不能使用連接和數據傳遞器來獲取這些信息嗎?

粗略(在你的命令的使用語句)

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(); 
    } 
}