In SQL Query how to set table name - c#

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.

Related

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 add multiple Datasets to Single DataTable?

I have below code, where in I am creating a dataset based on a query to Oracle mdb.
....
**OracleDataAdapter adapter = new OracleDataAdapter(sqlstr, conn);
OracleCommandBuilder builder = new OracleCommandBuilder(adapter);
DataSet dataset = new DataSet();
adapter.Fill(dataset);**
DataTable dataTable = dataset.Tables[0];
....
I would like to have the highlighted code in a loop, and then add the dataset objects to a common datatable outside the loop.
Do I need to use datatable.Merge()? The resultset in 'n' datasets need to be combined into a single DataTable, hence I am not sure Merge is the right way.
How can this be implemented?
Thanks
Presumably you are creating a new 'sqlstr' for each query to the Oracle mdb? If so you can create a list to put all your sqlstr into and then have a for loop to cycle through them like this:
List<string> sqlstrings = new List<string>();
//add your sqlstr's here
DataSet dataset = new DataSet();
for(int i = 0; i < sqlstrings.count; i++)
{
OracleDataAdapter adapter = new OracleDataAdapter(sqlstrings[i].ToString(), conn);
OracleCommandBuilder builder = new OracleCommandBuilder(adapter);
adapter.Fill(dataset.Tables[i]);
}
This will get all of your queries into 1 dataset with multiple tables. You can then create a data relation between all the tables as per here: http://msdn.microsoft.com/en-us/library/ay82azad(v=vs.110).aspx.
However, if you want to create just 1 DataTable then you can use 'Merge' as per the link supplied by Mithrandir. Of course, you would need to add this into the loop above and account for the first run (you can't merge table 1 with nothing). Create a new DataTable before the loop and do something like:
if(i > 0)
{
dtBigTable.Merge(dataset.Tables[i]);
}
else
{
//First table
dtBigTables = dataset.Tables[0]
}
Note: this is untested code. It's just to give you an idea and something to play with.

Different DataTables with one query?

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.

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;

How to add data to a new formed column

I am trying to add data to a newly created column...
DataSet ds = new DataSet;
ds.Tables[0].Columns.Add("Count");
Data.DataSource = ds;
Data.DataBind();
Where do I add, a hardcoded count? (I want count column to have '4')
You add data to rows - so:
DataSet ds = new DataSet();
DataTable table = ds.Tables.Add();
table.Columns.Add("Count", typeof(int));
table.Rows.Add(4);
However, there are probably easier options; a DataSet seems massively overkill to bind a single value.
It technically is a repeater function but if I get the hardcoded function... I can make the code to make it flexible. I got it to work. I was adding a column to an existing table. This is what I did...
for int i=0; i<ds.tables[0].Rows.Count; i++)
{
ds.tables[0].Rows[i]["Count"] = "4";
}

Categories