跟据查询语句集合升成一个DataTable对象

/// <summary>
    
/// 跟据查询语句集合升成一个DataTable对象
    
/// </summary>
    
/// <param name="selectSqls">查询语句集合</param>
    
/// <returns>查询结果</returns>
    public static DataTable GetDataForSqls(System.Collections.Generic.List<string> selectSqls) {
        
using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();
            
try
            {
                SqlCommand cmd 
= new SqlCommand();
                cmd.Connection 
= conn;
                cmd.CommandType 
= CommandType.Text;
                DataTable dt 
= new DataTable("wwmTable");
                
foreach (string selectSql in selectSqls)
                {
                    cmd.CommandText 
= selectSql;
                    SqlDataReader sdr 
= cmd.ExecuteReader();
                    
while (sdr.Read())
                    {
                        
for (int i = 0; i < sdr.FieldCount; i++){
                            
string columnName = sdr.GetName(i);
                            
if (dt.Columns.Contains(columnName)) continue;
                            dt.Columns.Add(columnName, sdr.GetFieldType(i));
                        }
                        DataRow dr 
= dt.NewRow();
                        
for (int i = 0; i < sdr.FieldCount; i++)
                        {
                            
string columnName = sdr.GetName(i);
                            dr[columnName] 
= sdr[i];
                        }

                        dt.Rows.Add(dr);
                    }
                    sdr.Dispose();
                }

                
return dt;
            }
            
catch (Exception ex)
            {
                
throw ex;
            }
            
finally { 
                
if (conn.State == ConnectionState.Open) conn.Close();
            }
        }
    }
posted @ 2009-03-05 10:28  文明的天空  阅读(152)  评论(0编辑  收藏  举报