From MS doc for DBDataAdapter.Fill:
When the query specified returns multiple results, the result set for each row returning query is placed in a separate table. Additional result sets are named by appending integral values to the specified table name (for example, "Table", "Table1", "Table2", and so on).
And I can see from the example for DataSet that they use Table:
//Create a SqlDataAdapter for the Suppliers table.
SqlDataAdapter adapter = new SqlDataAdapter();
// A table mapping names the DataTable.
adapter.TableMappings.Add("Table", "Suppliers");
// Open the connection.
connection.Open();
Console.WriteLine("The SqlConnection is open.");
// Create a SqlCommand to retrieve Suppliers data.
SqlCommand command = new SqlCommand(
"SELECT SupplierID, CompanyName FROM dbo.Suppliers;",
connection);
command.CommandType = CommandType.Text;
// Set the SqlDataAdapter's SelectCommand.
adapter.SelectCommand = command;
// Fill the DataSet.
DataSet dataSet = new DataSet("Suppliers");
adapter. Fill(dataset);
But are Table, Table1, Table2 and so on guaranteed? Can I safely use them when I want to set custom names for the DataSet tables with TableMappings?
Given the following two tables (in SQL Server):
Employee:
Asset:
Try the following:
Add the following using directives:
using System.Configuration;using System.Data;using System.Data.SqlClient;using System.Diagnostics;App.config:
GetData:
Update:
According to Populating a DataSet from a DataAdapter, it states:
Let's add some sample data:
Employee:
Asset:
If we execute the following code:
The output is:
As you can see, the table name is
Table, in both the 1st and 2nd query. Additionally, the column names from the 2nd query were added to the table (name: "Table") in the DataSet. The final result is a table with 3 + 4 = 7 rows. This isn't the desired result.Let's try with multiple result sets (ie: more than one select statement within a single SelectCommand). We'll use 2 select queries separated by semi-colon:
SELECT * FROM Employee; SELECT * FROM Asset;The output is:
This is one gives the desired result, however as stated in the documentation the table names are
TableandTable1.If one desires for each
DataTablewithin aDataSetto have the same name as the table within the database, one can use DataAdapter.TableMappings as shown below:The output is:
Notice that for each
DataTablewithin theDataSet, that the name now matches the name of table in the database (EmployeeandAsset).Summary:
Given:
SqlConnection con = new SqlConnection(_connectionStr)SqlDataAdapter da = new SqlDataAdapter()As demonstrated above, for a single result set (ie: a single select statement within a SelectCommand),
or
the result is the (default) DataTable name
Table.If one uses multiple result sets (ie: multiple select statements within a SelectCommand),
the result is the (default) DataTable names
Table,Table1, etc.., unless one adds a mapping using DataAdapter.TableMappings.Resources:
Additional Resources: