How to write select with case in datatable using c# - c#

I'm trying to filter the data in the datatable with some condition but the condition are using case condition as shown below
DataTable dt = (DataTable)ViewState["FilteredData"];
string expression = string.Format("MAKER_BY = CASE WHEN '" + MakerBy.Trim() + "'='A' THEN MAKER_BY ELSE '"+ MakerBy.Trim() + "' END");
dt = dt.Select(expression).CopyToDataTable();
When executing the above code I'm getting error saying, Missing operand after 'WHEN' operator.
Any help will be appreciated.
Thank you.

Filter expressions does not support CASE.
However, They do support IIF.
For more information, read the relevant Microsoft docs page: DataColumn.Expression Property.
So you can do it like this:
string expression = string.Format("MAKER_BY = IIF('" + MakerBy.Trim() + "'='A', MAKER_BY, '"+ MakerBy.Trim() + "')");
However, there is an easier way:
string expression = "MAKER_BY = '"+ MakerBy.Trim() +"' OR '"+ MakerBy.Trim() +"' = 'A'";

Related

How to get multiple wildcard % in the middle of a DataView RowFilter same as sql

I have this row filter text:
"[add1] = '" + startAddress+ "%" + middle+ "%" + end +"'"
which fails, but if I put the % at the beginning or end it's OK.
Is there any way to achieve the same result (i.e. "any" string in the middle of the names)?
Full statement is:
dv = new DataView(MyDataTable, "[add1] = '" + startAddress+ "%" + middle+ "%" + end + + "'", "", DataViewRowState.CurrentRows);
Here i want filteration like "%something%someone%" How can i achieve this? Even using linq is also ok with me

multiple Parameters - Syntax error in string in query expression: VS 2010 with MS-Access 2003

I am receiving
OleDBException was unhandled error of "Syntax error (missing operator) in query
expression '(StudentID = 100' OR StudentName = 'Nick' OR StudentCNCI = '78894452)Bob'."
private void btnFind_Click(object sender, EventArgs e)
{
string title = textBox1.Text.ToString();
string queryString = "SELECT * FROM Students WHERE (StudentID = " + StudIDTb.Text.ToString() + "' OR StudentName = '" + StudNameTb.Text.ToString() + "' OR StudentCNCI = '" + StudCNCITb.Text.ToString() + ")" + title;
OleDbCommand command = new OleDbCommand();
command.CommandText = queryString;
command.Connection = myCon;
myCon.Open();
OleDbDataReader dr = command.ExecuteReader(); // error pointing here
while (dr.Read())
{
StudIDTb.Text += String.Format("StudentID: {0}\n", dr["StudentID"].ToString());
StudNameTb.Text += String.Format("StudentName: {0}\n", dr["StudentName"].ToString());
StudCNCITb.Text += String.Format("StudentCNIC: {0}\n", dr["StudentCNIC"].ToString());
StudDOBTb.Text += String.Format("StudentDOB: {0}\n", dr["StudentDOB"].ToString());
}
myCon.Close();
}
I have also tried...
string queryString = "SELECT * FROM Students WHERE (StudentID = " + StudIDTb.Text + "' OR StudentName = '" + StudNameTb.Text + "' OR StudentCNCI = '" + StudCNCITb.Text + ")" + title;
I don't want to give you wrong impression I am "lazy" but I am assuming I am getting this error because I have query it incorrectly or I have made a typo error or could it be something else. Please can someone help me, thanks in advance.
ps I know I am getting criticism for not using parameterized queries. I will change it once I got the basic right. I know a lot of similar questions have been asked here but I still can't get it right.
UPDATE 1
I have changed it to
"SELECT * FROM Students WHERE StudentID = " + StudIDTb.Text + " OR StudentName = '" + StudNameTb.Text + "', OR StudentCNCI = '" + StudCNCITb.Text + ")";
I am now receiving error of...
Syntax error (comma) in query expression
I am looking into it
Update 2
string queryString = "SELECT * FROM Students WHERE StudentID = " + StudIDTb.Text + "' OR StudentName = '" + StudNameTb.Text + "' OR StudentCNCI = '" + StudCNCITb.Text + "'";
Receiving the same error.
Looking into it
Update 3
If it can't be solved I do it the way it should be, using parameterized queries as highly recommended if it means to solve the problem and probably easy to spot any problems with the code
It's telling you that your query is invalid. You have this
SELECT *
FROM Students
WHERE (StudentID='a' OR StudentName='b' or StudentCNCI='c')Bob
It's not liking that Bob on the end and it's not clear why you need it. Explain what your intent is there, or just get rid of it as it doesn't appear to be necessary for your query.
string queryString = "SELECT * FROM Students WHERE StudentID = '" +
StudIDTb.Text + "' OR StudentName = '" + StudNameTb.Text +
"' OR StudentCNCI = '" + StudCNCITb.Text + "'";
As you mention in your post, you need to parameterize your query also. Let us know if you need help with that, but it is pretty straightforward, and a common post on here, so you already have plenty of resources to figure that out.
EDIT: If you like, you can remove the parenthesis. You'd really only need then if you were going to do a subquery or some such thing. They won't hurt your query, they're just not really necessary.
SELECT *
FROM Students
WHERE StudentID='a' OR StudentName='b' or StudentCNCI='c'
Also, from other comments, you actually have multiple quote mismatches (one at the beginning and another at the end).

IDataReader not reading, no errors

I realize IDataReader is outdated and some view it as dirty code, but on the site I am working on this is what they use. I have an IDataReader statement to run a query to get a specific id from a table using multiple joins. Now this site has a DAL but it only supports the ability to select from one table at a time, so using select statements with joins do not work with it. This is why I am forced to use IDataReader with this.
if (Request.QueryString["CategoryId"].ToString() == "0")
{
using (IDataReader getCategoryID = DB.GetRS("SELECT ItemCatalogCategory.CategoryID FROM UserCustomerCatalog INNER JOIN ItemCatalogCategory ON UserCustomerCatalog.ItemProfileCatalogID = ItemCatalogCategory.ItemProfileCatalogID " +
"INNER JOIN ItemCategory ON ItemCatalogCategory.CategoryID = ItemCategory.CategoryID INNER JOIN StoreCatalog ON UserCustomerCatalog.StoreCatalogID = StoreCatalog.StoreCatalogID " +
"WHERE UserCustomerCatalog.ItemProfileCatalogID = '" + Request.QueryString["CatalogID"] + "' AND UserCustomerCatalog.CustomerID =' " + Session["Customer"].ToString() + "' AND ItemCategory.ProductID = '" + productis + "'"))
{
if (getCategoryID.Read())
{
string categoryID = getCategoryID["ItemCatalogCategory.CategoryID"].ToString();
string lookmike = Request.Url.AbsolutePath + "?CatalogID=" + catalogis + "&ProductID=" + productis + "&CatalogIndex=" + Request.QueryString["CatalogIndex"] + "&CategoryID=" + categoryID;
Response.Redirect(Request.Url.AbsolutePath + "?CatalogID=" + catalogis + "&ProductID=" + productis + "&CatalogIndex=" + Request.QueryString["CatalogIndex"] + "&CategoryID=" + categoryID);
}
else
{
Response.Redirect(Request.Url.AbsolutePath + "?CatalogID=" + catalogis + "&ProductID=" + productis + "&CatalogIndex=" + Request.QueryString["CatalogIndex"] + "&CategoryID=" + Request.QueryString["CategoryId"]);
}
}//end using getCategoryID
}
this is what I have, but when it gets to:
if (getCategoryID.Read())
it renders as false, there are no exceptions thrown, and no errors or warnings. I have done this type of select in the past with no problems, but I cannot figure out why .Read() is returning false.
Can anyone suggest possible reasons for it not reading? If more code is needed, I can provide as needed. Any help is appreciated, thank you in advance.
Looking at your SQL text there is a little typo that could wreak havoc with the results
"WHERE UserCustomerCatalog.ItemProfileCatalogID = '" + Request.QueryString["CatalogID"] +
"' AND UserCustomerCatalog.CustomerID =' " + Session["Customer"].ToString() + "' AND ..... "
here ^
That space mangles your query and give no result.
Let me also repeat that you have a problem with SQL Injection as other members have already said. You could add an overload to your actual implementation of GetRS that receive also a SQLParameter collection to add to the command used to build your SqlDataReader. Something like this
public SqlDataReader GetRS(string sqlText, SqlParameter[] prm)
{
....
SqlCommand cmd = new SqlCommand(sqlText, conn);
cmd.Parameters.AddRange(prm);
.....
}
and then start to upate the calling code.

Read Data from data set

I have data set that is being filled from sql query, like this
cmd_sql.CommandText = " SELECT BrDok " +
" FROM ordersstavke " +
" WHERE SifParFil = '" + rw_mat["sifskl_kor"] + "'";
MySqlDataAdapter sql_adapter = new MySqlDataAdapter(cmd_sql);
DataSet ds_dok = new DataSet("ordersstavke");
sql_adapter.Fill(ds_dok);
Now I want to extract value from data set for sql update, like this one
myQuery = "UPDATE ordersstavke " +
"SET BrDok = '" + rw_mat["brdok"] + "', " +
"SifParFil = '" + rw_mat["sifskl_kor"] + "', " +
"WHERE BrDok = " + ds_dok.Tables["ordersstavke"].Rows[0]["BrDok"] + "'";
I tried this ds_dok.Tables["ordersstavke"].Rows[0]["BrDok"] but I got an error,
I was thinking to do something like this
string BrDok;
BrDok = ds_dok.["BrDok"].ToString();
But nothing, how to extract that BrDok or just put it into procedure?
Thanks infront!
Make it
DataSet ds_dok = new DataSet("ordersstavke");
sql_adapter.Fill(ds_dok,"BrDok");
Then use
ds_dok.Tables["BrDok"].Rows[0]["BrDok"].ToString()
Try this
ds_dok.Tables[0].Rows[0]["BrDok"]
If you provide a string argument for the dataset class, then it will be the dataset name and not the datatable name. And there is no table in the database with name you provided for a dataset, so give it while filling the dataset. Write some thing like below.
DataSet ds_dok = new DataSet();
sql_adapter.Fill(ds_dok,"ordersstavke");
and you can write all the remaining code as it is in your code part.
And your second update query has some syntax error, see it like below
myQuery = "UPDATE ordersstavke " + "SET BrDok = '" + rw_mat["brdok"] + "', "
+ "SifParFil = '" + rw_mat["sifskl_kor"] + "', " + "WHERE BrDok
= '" + ds_dok.Tables["ordersstavke"].Rows[0]["BrDok"] + "'";
You forgot to put an starting inverted comma at the where clause.
Just a small hint to the sql-command. You should use sql-parameters to prefent sql-injection.

DataTable.Select() - Comparing GUIDs

I've a datatable with a column containing GUIDs. I want to select a row matching a specific GUID. I wrote the following code,
DataRow[] dRows = dtListSettings.Select("ListGUID = " + Convert.ToString(ViewState["GUID"]));
The GUID i'm comparing is 500c2b6a-a3a7-457f-90ed-c96768d91520. But i'm getting the error - Syntax error: Missing operand after 'c2b6a' operator.
Any ideas?
Thank you
NLV
Need a single quote:
Something like:
string.Format("ListGUID = '{0}'", Convert.ToString(ViewState["GUID"]));
Try surrounding your select statement parameter in single quotes, like this:
DataRow[] dRows = dtListSettings.Select("ListGUID = '" + Convert.ToString(ViewState["GUID"]) + "'");
This does not work for IN. E.g.
DataRow[] dRows = dtListSettings.Select("ListGUID IN ('" + Convert.ToString(ViewState["GUID"]) + "')");
I resolve this with two bellow methods:
DataTable dt = new DataTable(); // your datatable with data
Guid gid = Guid.NewGuid(); // searching guid
DataRow[] dra = dt.Select("GuidColumn = '" + gid.ToString() + "'")
// OR
DataRow[] dra = dt.Select("GuidColumn = Convert('" + gid.ToString() + "', 'System.Guid')");
hope be useful ;)

Categories

Resources