Say if I populate a DataTable with a SQL command like this:
SQLCmd.Parameters.AddWithValue("#Date",DateTime.Today());
SQLCmd.CommandText = #"select ID, Name, Date from TestTable1 where Date=#Date";
SqlDataAdapter SQLAdapter = new SqlDataAdapter(SQLCmd);
DataTable dt = new DataTable();
SQLAdapter.Fill(dt);
Is it possible do a further query looking for something in another table which is also in dt?
For example, do something like
select ID
from TestTable2
where TestTable2.ID = dt["ID"];
Something like that... assuming both TestTable1 and TestTable2 have a column ID.
Thanks for helping!
You could use linkserver to get the data at a time or else below code may help you out. Get all the IDs with "," separated and passed it to second query.
string ids = String.Join(",", dt.AsEnumerable().Select(x => x.Field<int>("ID").ToString()).ToArray());
SQLCmd.Parameters.AddWithValue("#ID",ids);
SQLCmd.CommandText = #"select ID from TestTable2 where ID in ("+#ID+")";
SqlDataAdapter SQLAdapter = new SqlDataAdapter(SQLCmd);
DataTable dt2 = new DataTable();
SQLAdapter.Fill(dt2);
Just as an alternative option to think about, you could JOIN TestTable2 like:
SELECT t1.[ID]
,t1.[Name]
,t1.[DATE]
,t2.[ID]
FROM TestTable1 t1
INNER JOIN TestTable2 t2 ON t1.ID = t2.ID
WHERE t1.[DATE] = #Date
You can filter using DataView
DataView dv = new DataView(dt);
dv.RowFilter = "query"; // query example = "DATE = 'Your Date'"
Related
I searched a lot but could not find the right solution.
Lets say ill select data like:
using(MySqlConnection connection = new MySqlConnection(MyConnectionString))
using(MySqlCommand cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText = "SELECT a.Id, a.Foo, b.Bar FROM tableA a, tableB b where a.Id = b.Id";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[...]; //<== here is the problem
}
and I want to add this to a datatable,
How do I call the table in this case ?
Is it tableA ?
Does it matters how I name it ? (could I name it foobar as well???)
It is unclear what you are really asking for, but due to the length of comment and clarification, putting into an answer.
If you are trying to get multiple query results back from MySQL into a single "DataSet" (which can contain multiple tables), your query could contain multiple sql-statements and each would be returned into the dataset for you as different table results. For example, if you did something like...
using(MySqlConnection connection = new MySqlConnection(MyConnectionString))
using(MySqlCommand cmd = connection.CreateCommand())
{
connection.Open();
cmd.CommandText =
#"select * from TableA;
select * from TableB;
SELECT a.Id, a.Foo, b.Bar FROM tableA a, tableB b where a.Id = b.Id;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
}
Your dataset would have 3 tables in it in direct correlation of the queries provided..
ds.Tables[0] = result of tableA all records.
ds.Tables[1] = result of tableB all records.
ds.Tables[2] = result of JOIN query tableA and tableB.
you could then refer to them locally however you need to...
ds.Tables[0].TableName = "anyLocalTableNameReference".
var t1Recs = ds.Tables[0].Rows.Count;
etc... or even create your own individual datatable variable name without having to explicitly reference the dataset and table array reference
DataTable myLocalTableA = ds.Tables[0];
DataTable myLocalTableB = ds.Tables[1];
DataTable myJoinResult = ds.Tables[2];
Hopefully this clarifies a bunch with the querying and referencing of multiple data results returned and how to then reference to the tables individually.
I know it is a repeated question but i have tried much but i am getting exception
$exception {"String was not recognized as a valid DateTime."} System.Exception {System.FormatException}
Following is my code please check and guide
SQL QUERY
SELECT gangId as gang, respectPoints as respectPoints,DATE_FORMAT( purchasedDate, '%d-%m-%Y') as date_purchase FROM tbl_gang t where gangId=" + gangId
Data Access Layer Code
DataTable dt = new DataTable();
MySqlCommand cmd = conn.CreateCommand();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
cmd.CommandText = inAppPurchaseQuery;
da.Fill(dt)
Sorting Code
dt = gangRPObj.getGangRPLogsBL(gangId, fromDate, toDate);
var sortedTable = dt.AsEnumerable()
.OrderBy(r => DateTime.ParseExact(("date_purchase"),
"dd-mm-yyyy", null))
.CopyToDataTable();
Thanks
You are passing string to datetime conversion that's why exception is coming. Try
var orderedRows = from row in dt.AsEnumerable()
let date = DateTime.ParseExact(row.Field<string>("date_purchase"),"dd-mm-yyyy", null)
orderby date
select row;
Sorting a date-column as string also doesn't sort correctly. You should also sort in the database instead of in memory and use parameters instead of string concatenation to prevent sql-injection and date-conversion-issues like this.
string sql = #"SELECT gangId as gang,
respectPoints as respectPoints,
DATE_FORMAT(purchasedDate, '%d-%m-%Y') as date_purchase,
FROM tbl_gang t
WHERE gangId=#gangId
ORDER BY purchasedDate ASC";
using (var cmd = new MySqlCommand(sql, conn))
using (var da = new MySqlDataAdapter(cmd))
{
da.SelectCommand.Parameters.Add("#gangId", MySql.Data.MySqlClient.MySqlDbType.Int32).Value = gangID;
da.Fill(dt); // no need to order this on client side
}
How do I display the value of column Department from tblDepartment to tblEmployee in a webform table? I have this code but it only displays the DeptID.
This is the Page_load code
sConn = new SqlConnection(sStr);
daEmp = new SqlDataAdapter("SELECT * FROM tblEmployee", sConn);
daDep = new SqlDataAdapter("SELECT * FROM tblDepartment", sConn);
dsEmp = new DataSet();
dsDep = new DataSet();
daEmp.Fill(dsEmp, "tblEmployee");
daDep.Fill(dsDep, "tblDepartment");
dsEmp.Tables["tblEmployee"].PrimaryKey = new DataColumn[] { dsEmp.Tables["tblEmployee"].Columns["EmployeeID"] };
DataTable dt = new DataTable();
dgvEmployee.DataSource = dsEmp.Tables["tblEmployee"];
dgvEmployee.DataBind();
These are the tables
When you need to display information from two or more different tables you can join them based on relationship(primary key and foreign key) columns:
You need to Replace this Query:
SELECT * FROM tblEmployee
With this:
SELECT employee.*,department.Department
FROM tblEmployee employee
INNER JOIN tblDepartment department ON employee.DeptID=department.DeptID
I have a Session, which is list int, and I need to make a query that will take from a database only those rows that have the PK value that exists in Session.
I was thinking of doing it with the IN function, or making a new datatable with 1 collumn and values from the Session and doing a double join, probably left...
I just dont know how to make a table from a list.
What I have so far:
String ConnString = "Data Source=BRACO-PC\SQL1;Initial Catalog=DiplomskiSQL1SQL;Integrated Security=True";
SqlConnection Conn = new SqlConnection(ConnString);
Conn.Open();
DataTable ukosarici = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("Select Proizvodi.ime, TipProizvoda.tip, Proizvodi.dimenzije, Proizvodi.cijena from Proizvod LEFT JOIN TipProizvoda On Proizvod.tip=TipProizvoda.id_t WHERE Proizvod.id_p IN ", Conn);
SqlCommandBuilder cmd = new SqlCommandBuilder(da);
da.Fill(ukosarici);
GridView1.DataSource = ukosarici;
GridView1.DataBind();
Conn.Close();
Create a temporary table or table variable, insert the ints into it using INSERT or BULK INSERT, do a join in the SQL query then drop the temp table or table variable.
There are many ways you could do this, but one of my preferred methods is to serialize the list to a CSV, e.g. '1,3,5,33'. I then use a custom SQL Table function to de-serialize the list and filter in the database:
SELECT * FROM mytable t
JOIN dbo.ufn_CSVtoTextList('1,3,5,33' , ',') csv
ON csv.[Entry] = t.Id
The ufn_CSVtoTextList function CREATE script is below:
CREATE FUNCTION [dbo].[ufn_CSVToTextlist] ( #StringInput nVARCHAR(max) ,#SepChar nchar(1) = ',')
RETURNS #OutputTable TABLE ( [Entry] nVarchar(255), [index] int identity (0,1) )
AS
BEGIN
DECLARE #Entry nVarChar(255)
WHILE LEN(#StringInput) > 0
BEGIN
SET #Entry = LEFT(#StringInput,
ISNULL(NULLIF(CHARINDEX(#SepChar, #StringInput) - 1, -1),
LEN(#StringInput)))
SET #StringInput = SUBSTRING(#StringInput,
ISNULL(NULLIF(CHARINDEX(#SepChar, #StringInput), 0),
LEN(#StringInput)) + 1, LEN(#StringInput))
INSERT INTO #OutputTable ( [Entry] )
VALUES ( #Entry )
END
RETURN
END
Try by changing your SqlDataAdapter Call as follows
List<int> list ; // Assign with your session int list values
List<string> l2 = list.ConvertAll<string>(delegate(int i) { return i.ToString(); });
string query = "Select Proizvodi.ime, TipProizvoda.tip, Proizvodi.dimenzije, Proizvodi.cijena from Proizvod LEFT JOIN TipProizvoda On Proizvod.tip=TipProizvoda.id_t WHERE Proizvod.id_p IN (";
query = query + string.Join(",", l2.ToArray()) + ")";
SqlDataAdapter da = new SqlDataAdapter(query, Conn);
How can I select specific columns from excel sheet rather than all columns
string connectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", txtPath.Text);
string query = String.Format("select * from [{0}$]", "Sheet1");
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataGridView1.DataSource = dataSet.Tables[0];
What about:
SELECT * FROM [Sheet1$B14:C20]
This should select cells B14 to C20.
This will sound trivial but this is what I understand from your question. Instead of SELECT * use SELECT [columnName1],[columnName2] FROM Sheet1.. Here columnName1 and columnName2 should be the headers of columns that you want to get from Excel Sheet.
If you want to select the data before populating here is a good reference on advanced select statements. If you want to manipulate your data post populating your DataSet then here's how:
DataTable myTable = dataSet.Tables[0];
var myColumn = myTable.Columns["ColumnName"];
or
var myColumn = myTable.Columns[0];
To access a single field it would look something like this.
var field = myTable.Rows[0][myColumn];