Different DataTables with one query? - c#

Let's say I have two tables, Customer and Customer_address. To populate one datatable from a query is trivial, but is it possible to populate two different datatables via one join query?
Example:
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand("SELECT a.CustomerID, b.CustomerEmail FROM Customer a INNER JOIN Customer_address b ON a.CustomerID = b.CustomerID WHERE a.CustomerID = 3", this.connection);
DataSet ds = new DataSet();
adapter.Fill(ds, "Customer");
Now I have CustomerID and CustomerEmail in ds.Tables["Customer"].
Is it possible to have CustomerID in Tables["Customer"] and CustomerEmail in Tables["Customer_address"] without making two distinct queries?

Have a look at MSDN:
"Multiple Result Sets:
If the DataAdapter encounters multiple result sets, it creates multiple tables in the DataSet. The tables are given an incremental default name of TableN, starting with "Table" for Table0. If a table name is passed as an argument to the Fill method, the tables are given an incremental default name of TableNameN, starting with "TableName" for TableName0."
So no, you can't specify the correct table name for the second table since it's derived from the single parameter in Fill.

Related

In Data table first column displaying with tablename.columnname in c#

When i am running query in data base and fill data table with load method first column name coming with table name.column name(Employee.Name,sal,location) rest of the column name coming only column names present in the database.Why table name appending first column name while displaying in data table structure please help me in this regards.
DataTable table = new DataTable();
try
{
using (IDbCommand DbCommand = dbConnection.CreateCommand())
{
DbCommand.CommandText = query;
IDataReader reader = DbCommand.ExecuteReader();
table.Load(reader);
}
}
Sample query Select Employee.Numnber, Employee.salary, Employee.city,dept.deptId from Employee inner join dept where deptiId=EmployeeDeptId
The actual query is :
Select
AP_LINE.LINE_NO, AP_LINE.PRODUCT, AP_LINE.QTY, AP_LINE.REQUESTED_DATE,
AP_LINE.LIST_PRICE, AP_LINE.CONS_NET_MULT,AP_LINE.NETADDERS,
AP_LINE.CONS_NET_PRICE, AP_LINE.Details,TDP_JSP.ID, TDP_JSP.LINE_NO,
TDP_JSP_AppInfo.Id
From AP_LINE, CONFIG, TDP_JSP
inner join TDP_JSP_AppInfo on TDP_JSP.ID= TDP_JSP_AppInfo.ID
where AP_LINE.LINE_NO = TDP_JSP.LINE_NO ;
Out put in data table as coming below
Ap_Line.Line_No,Product,QTY,Requested Date...
There are two LINE_NO columns in the query, AP_LINE.LINE_NO and TDP_JSP.LINE_NO. Columns must have unique names, so DataTable.Load used the two-part name wherever needed. It that wasn't possible it would start appending indexes or even generate names like Column0, Column1 etc.
In this case though, one of those columns isn't needed. The two tables are join those columns. WHERE AP_LINE.LINE_NO = TDP_JSP.LINE_NO is the old-style, frowned-upon join syntax. Those two columns will always have the same data so one of them can be removed.

C# 1 datagridview 2 databases where statement

Is it possible to add data from 2 tables in 1 datagridview.
And let table 2 add information that is equal with row[0].
The problem is Name is in another table as the needed information but ID's are matching.
Table 1 got : ID,Time and some other stuff.
Table 2 got : ID,Name.
So he needs to get the ID from row 0 and with Table 2 He needs to get the name WHERE ID is equal to Row 0
Yes it is possible to place two tables into the same datagridview. Run a query like this..
Select ID, name
From Table2
Where ID IN (
Select Top 1
ID
Table1
)
And then use this to fill a datatable, and set that as the data source of the datagridview.
Dont try to mess with DataGridView, Here is simple Solution based on ADO.NET
string select = "SELECT * FROM table1,table2 WHERE table1.ID=table2.ID";
MySqlConnection c = new MySqlConnection();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(select, c.con); //c.con is the connection string
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView.DataSource = ds.tables[0];

How to combine 2 datatable and create a new datatable with that in Windows application?

I have 2 datatable DataTable1 and DataTable2, DataTable1 have the column as A,B,C,D and DataTable2 has the Column as P,Q,R,S I want to add both the datatable column and want to create a new datatable as A,B,C,D,P,Q,R,S
Some one please help me how to do that
You can merge 2 tables like this
var dtA = new DataTable();
dtA.Columns.Add("A");
dtA.Columns.Add("B");
dtA.Columns.Add("C");
var dtB = new DataTable();
dtB.Columns.Add("D");
dtB.Columns.Add("E");
dtB.Columns.Add("F");
dtA.Merge(dtB);
This is not practical, and bad design.
Simply because you cannot take two different things and bring them together without "commonality" as the Stig mentioned in his comment.
Think about bring together 2 datatables, one has 5 rows and the other as 100.
Unless there is something to join them by, I wouldn't suggest trying to do this.
Alternatively if you must have functionality, then I suggest you iterate through the datatables building a new datatable consisting of Datable1 and DataTable2.
Below is sample of Join:
from table1 in dt1.AsEnumerable()
join table2 in dt2.AsEnumerable() on table1["Location"] equals table2["Location"]
select new
{
Location = table1["Location"],
Visa_Q1 = (int)table1["Visa_Q1"],
Visa_Q2 = (int)table1["Visa_Q2"],
Visa_Q3 = (int)table2["Visa_Q3"],
Visa_Q4 = (int)table2["Visa_Q4"],
};

Is it possible to order data in a datatable by a related datatable in the dataset?

I've been using ORM's for so long, I appear to have forgotten most of my basic data handling skills in dotnet :(
Is it possibly to do something like this?
DataSet ds = new DataSet();
var compiledConnection = new SqlConnection(cDbConnectionString);
SqlDataAdapter daChart = new SqlDataAdapter("select * from Chart", compiledConnection);
daChart.Fill(ds, "chart");
if (ds.Tables["chart"].Rows.Count > 0)
{
var sourceConnection = new SqlConnection(sourceDbConnectionString);
SqlDataAdapter daSource = new SqlDataAdapter("select * from source", sourceConnection);
daSource.Fill(ds, "source");
DataRelation chart_source = new DataRelation("dr", ds.Tables["chart"].Columns["intItemId"],
ds.Tables["source"].Columns["intRowId"], false);
ds.Relations.Add(chart_source);
}
And then use one of the columns in the table "chart" to order the data in the table "source" across the datarelation?
(Before anyone asks, these two tables are in separare instances of SqlServer on separate sites, so just pulling the data as one table is not a straightforward task. Hence this approach)
Cheers,
Matt
That just creates the equivalent of a foreign key. You seem to want the equivalent of an INNER JOIN.
In addition to creating the relationship, it requires adding all the columns of one to the other, loops to fill in the rows and GetParentRows. MS has some good starting point code:
http://support.microsoft.com/kb/326080
EDIT. You could also do a SQL version, by creating a linked server and using 4 part names [server].[database].[owner].[table]
Thanks for the suggestion, but I discovered you can do it with LINQ rather more easily:
DataTable source = ds.Tables["source"];
DataTable chart = ds.Tables["chart"];
var joinedTable =
from s in source.AsEnumerable()
join c in chart.AsEnumerable()
on s.Field<Int64>("intRowId") equals
c.Field<Int64>("intItemId")
select new
{
intRowId = s.Field<Int64>("intRowID"),
strTitle = s.Field<string>("strTitle"),
intWeight = c.Field<Int64>("intWeight")
};
var sortedTable = from j in joinedTable
orderby j.intWeight descending
select j;

In SQL Query how to set table name

I use C#. I fill a dataset with the result of sql query. Suppose ds is my dataset:
Dataset ds = new Dataset();
ds = GetTablesFromDataBase("Select * from Order, Select * from OrderDetails, Select * from Product");
After running the code above, my dataset contains three tables named Table, Table1, Table2. But I want my dataset table names to be the same as database tables names like: Order, OrderDetails, Product. Is there any way to write query or code, so that dataset table names become the same as database table names?
Please, don't propose the code below to change the table names of a dataset:
Dataset.TableName = "RequiredTableName";
You can use typed datasets or tablemapping
something like this
SqlDataAdapter da = new SqlDataAdapter(...);
DataSet ds = new DataSet();
DataTableMapping dtm1, dtm2, dtm3;
dtm1 = da.TableMappings.Add("Table", "Employees");
dtm2 = da.TableMappings.Add("Table1", "Products");
dtm3 = da.TableMappings.Add("Table2", "Orders");
da.Fill(ds);
you should probably use the DataTable class instead. Here is the mSDN reference for the same: http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx
It lets you define all the properties that you want plus give you lot more functions to work with the table.
and since you seem to like having all the tables in one class I would suggest you create a DTO that basically resembles whatever property you wanted to use of the DataSet class and add IList as one of the properties of this DTO.
Hope that makes sense and helps you.
ds.Tables[0].TableName = "Required Table Name";
ds.Tables[1].TableName = "Required Table Name";
ds.Tables[2].TableName = "Required Table Name";
You can use this method.
You could return the names of the tables with an separate select.
SELECT 'Employees','Orders';
SELECT * FROM Employees;
SELECT * FROM Orders;
(you could also select the Tablenames from the global systemtables...)
Then you can set the Tablenames in your DataSet automatically:
for (int cIdx = 0; cIdx < ds.Tables[0].Columns.Count; ++cIdx) {
int tIdx = cIdx + 1;
if (tIdx >= ds.Tables.Count) {
break;
}
ds.Tables[tIdx].TableName = ds.Tables[0].Rows[0][cIdx].ToString().Trim();
}
ds.Tables.RemoveAt[0];
This is also only a workaround, but I don't know a better way.

Categories