您可以将TableMappings 用于您的DataAdapter 以获得正确的表名:
using (var con = new SqlConnection(connectionString))
{
string sql = @"SELECT * FROM locGSP;
SELECT * FROM locCountry;
SELECT * FROM locMarketUnit";
using(var da = new SqlDataAdapter(sql, con))
{
// demonstrate the issue here:
DataSet dsWrong = new DataSet();
da.Fill(dsWrong); // now all tables are in this format: Table,Table1,Table2
// following will map the correct names to the tables
DataSet dsCorrect = new DataSet();
da.TableMappings.Add("Table", "locGSP");
da.TableMappings.Add("Table1", "locCountry");
da.TableMappings.Add("Table2", "locMarketUnit");
da.Fill(dsCorrect); // now we have the correct table-names: locGSP,locCountry,locMarketUnit
}
}
这是使用DataReader 和DataSet.Load 填充DataSet 的另一种方式:
using (var con = new SqlConnection(connectionString))
{
string sql = @"SELECT * FROM locGSP;
SELECT * FROM locCountry;
SELECT * FROM locMarketUnit";
using (var cmd = new SqlCommand(sql, con))
{
con.Open();
using (var rdr = cmd.ExecuteReader())
{
// after the next line the DataSet will have the correct table-names
ds.Load(rdr, LoadOption.OverwriteChanges, "locGSP", "locCountry", "locMarketUnit");
}
}
}
背景:
Populating a DataSet from a DataAdapter
Multiple Result Sets:如果DataAdapter遇到多个结果
集,它会在 DataSet 中创建多个表。表格已给出
TableN 的增量默认名称,以“Table”开头
表 0。如果将表名作为参数传递给 Fill 方法,
表被赋予一个递增的默认名称 TableNameN,
以 TableName0 的“TableName”开头。