2009-06-17 50 views
1

我從多個表收集數據,如補充水分,我的業務對象,MARS VS NextResult

 
SELECT * FROM CaDataTable; 
SELECT * FROM NyDataTable; 
SELECT * FROM WaDataTable; 

等等... (C#3.5,SQL Server 2005中)

我一直在使用批次:

void BatchReader() 
    { 
     string sql = "Select * From CaDataTable" + 
        "Select * From NyDataTable" + 
        "Select * From WaDataTable"; 

     string connectionString = GetConnectionString(); 
     using (SqlConnection conn = new SqlConnection(connectionString)) { 
      conn.Open(); 
      SqlCommand cmd = new SqlCommand(sql, conn); 
      using (SqlDataReader reader = cmd.ExecuteReader()) { 
       do { 
        while (reader.Read()) { 
         ReadRecords(reader); 
        } 
       } while (reader.NextResult()); 
      } 
     } 
    } 

我也用對相同的連接多個命令:

void MultipleCommandReader() 
    { 
     string connectionString = GetConnectionString(); 
     string sql; 
     SqlCommand cmd; 
     using (SqlConnection conn = new SqlConnection(connectionString)) { 
      conn.Open(); 

      sql = "Select * From CaDataTable"; 
      cmd = new SqlCommand(sql, conn); 
      using (SqlDataReader reader = cmd.ExecuteReader()) { 
       while (reader.Read()) { 
        ReadRecords(reader); 
       } 
      } 

      sql = "Select * From NyDataTable"; 
      cmd = new SqlCommand(sql, conn); 
      using (SqlDataReader reader = cmd.ExecuteReader()) { 
       while (reader.Read()) { 
        ReadRecords(reader); 
       } 
      } 

      sql = "Select * From WaDataTable"; 
      cmd = new SqlCommand(sql, conn); 
      using (SqlDataReader reader = cmd.ExecuteReader()) { 
       while (reader.Read()) { 
        ReadRecords(reader); 
       } 
      } 
     } 
    } 

這些技術之一是否明顯優於其他技術? 另外,如果我在第二種方法上使用MARS會有收益嗎?換句話說,是否像在連接字符串中設置MultipleActiveResultSets = True一樣簡單並且獲得了很大的好處?

回答

2

如果數據結構是每個表中的一樣,我會做:

Select *, 'Ca' Source From CaDataTable 
union all 
Select *, 'Ny' Source From NyDataTable 
union all 
Select *, 'Wa' Source From WaDataTable 
+0

謝謝,這是一個很好的選擇。如果我不確定每個表是否存在,是否有編碼的方法?換句話說,如何防禦NyDataTable不存在的情況呢? – Sisiutl 2009-06-17 19:24:19

0

沒有實際定時兩個版本針對彼此,你只能猜測....

希望打賭,版本1(BatchReader)會更快,因爲你只有一次往返數據庫。第2版​​需要三個不同的往返行程 - 每執行一次查詢都會有一個往返行程。

但是,你只能真的告訴你,如果你測量。

馬克

哦,PS:當然在現實生活場景的同時也將有助於使限制列返回,例如請勿使用SELECT *,而應使用SELECT (list of fields)並儘可能縮短字段列表。