2009-06-17 44 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)并尽可能缩短字段列表。