DataTable.Select() - Comparing GUIDs - c#

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 ;)

Related

How to write select with case in datatable using 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'";

Returning on ISNULL decimal "0,00"

Hello I have got this query that I would like to return '0,00' insead of '0'
When I tried to write it like this:
string sqlcom = "SELECT (ISNULL(s_prijmy, 0,00)), * FROM zajezd WHERE akce >= '" + txt_od.Text + "'AND akce <='" + txt_do.Text + "' AND rocnik='" + klientClass.Rocnik() + "'";
It gives me following Exception:
System.InvalidCastException: Specified cast is not valid. at
System.Data.SqlClient.SqlBuffer.get_Decimal()
May I ask how can I fix it ?
Thanks in adavance.
Future use of this '0,00' should be following :
this.chart1.Series["Příjmy"].Points.AddXY(myreader.GetString(myreader.GetOrdinal("akce")), myreader.GetDecimal(34).ToString()); // the 34th column
Change , with . in your query.
ISNULL(s_prijmy, 0.00)
I would also note that
GetDecimal(34)
gets the 35th column as it is zero-based...
Use:
GetDecimal(33)
for the 34th column.
Check here
0,00 is not decimal. Try 0.00 to cast it into the decimal in your query. And don't forgot to put 0.00 in single quotes '' if s_prijmy is type of varchar.
Try this
string sqlcom = "SELECT (ISNULL(s_prijmy, '0.00')), * FROM zajezd WHERE akce >= '" + txt_od.Text + "'AND akce <='" + txt_do.Text + "' AND rocnik='" + klientClass.Rocnik() + "'";
And yes as I already said the please try to use parameterized query.
What datatype is s_prijmy? if it is string, and you want to return a string of '0.00' then do
ISNULL(s_prijmy, '0.00')
If it is numeric, and you want to return a number in format 0.00, then do
ISNULL(s_prijmy, cast(0 as decimal(3,2)))
if s_prijmy has a greater precision that 2, eg decimal(4,3), then you will get 0.000
Try this way:
string sqlcom = "SELECT cast(ISNULL(s_prijmy, 0) as decimal(8,2)), * FROM zajezd WHERE akce >= '" + txt_od.Text + "'AND akce <='" + txt_do.Text + "' AND rocnik='" + klientClass.Rocnik() + "'";
You can format the data when you display it.
select the data as it is
string sqlcom = "SELECT s_prijmy, .........
then
var value = myreader.GetString(myreader.GetOrdinal("s_prijmy"));
value = string.IsNullOrEmpty(value)?"0,00":value;
now you can use above value in Points.AddXY
You must correct your presentation at client side. Look at the public string ToString(string format). Also here and here.

DataTable Select Implementation with Multiple AND Conditions

I have a DataTable with about 50,000 rows that I'm using DataTable.Select to retrieve rows from. The Select requires multiple AND conditions including a wildcard match. I've played around and found that by doing the same Select in multiple steps, the execution time can be greatly reduced, but changing the order of the AND statements doesn't affect it.
//This takes ~ 750 ms
DataRow[] results = myDataTable.Select("Field1 LIKE '*" + term1 + "*'" +
"AND Field2 = '" + term2 + "'" +
"AND Field3 = '" + term3 + "'");
//This also takes ~750 ms
DataRow[] results2 = myDataTable.Select("Field3 = '" + term3 + "'" +
"AND Field2 = '" + term2 + "'" +
"AND Field1 LIKE '*" + term1 + "*'");
//This takes 0.415 ms
DataTable table1 = myDataTable.Select("Field3 = '" + term3+ "'").CopyToDataTable();
DataTable table2 = table1.Select("Field2 = '" + term2 + "'").CopyToDataTable();
DataRow [] results3 = table2.Select("Field1 LIKE '*" + term1 + "*'");
My question is, is there a way to always make the SELECT operation evaluate AND conditions in a left-to-right order so that number of records searched would be reduced between steps? It would seem this could be a good time saver. Thank you for your ideas.
You could use Linq (note that the slowest condition is the last):
IEnumerable<DataRow> rows = myDataTable.AsEnumerable()
.Where(r => r.Field<string>("Field2") == term2
&& r.Field<string>("Field3") == term3
&& r.Field<string>("Field1").Contains(term1));
Use CopyToDataTable if you want to create a new DataTable from the result, ToArray to create a DataRow[] or leave it and use foreach to enumerate the result without creating a new collection.
Nope.. a datatable does a select row by row.
You can write your code a bit shorter:
DataRow [] results = myDataTable
.Select("Field3 = '" + term3+ "'").CopyToDataTable()
.Select("Field2 = '" + term2 + "'").CopyToDataTable()
.Select("Field1 LIKE '*" + term1 + "*'");
Or... if you make an extra extension method, like this:
static public DataRow[] Select(this IEnumerable rows, string filter)
{
return rows.CopyToDataTable().Select(filter);
}
Using this extension makes your code even shorter:
DataRow [] results = myDataTable
.Select("Field3 = '" + term3+ "'")
.Select("Field2 = '" + term2 + "'")
.Select("Field1 LIKE '*" + term1 + "*'");
Or:
static public DataRow[] Select(this DataTable dt, string firstFilter, params string[] filters)
{
DataRow[] result = dt.Select(firstFilter);
foreach(string filter in filters)
result = result.CopyToDataTable().Select(filter);
return result;
}
Opening up the way to:
DataRow [] results = myDataTable.Select(
"Field3 = '" + term3+ "'",
"Field2 = '" + term2 + "'",
"Field1 LIKE '*" + term1 + "*'");

MySQL Returning Column Names instead of their Content

Okay, so in the past few weeks I've probably written about 40 select statements. So, I know how to do it. And I've just written another one, but this time I need to use ComboBox values to match against, and it keeps resulting in the names of the column (the right column, mind you), instead of what's inside the column.
string st = "SELECT '" + txtchange.Text + "'
FROM mysql_9269_dbase." + pages.Text + "";
MySql.Data.MySqlClient.MySqlCommand cd = new MySql.Data.MySqlClient.MySqlCommand(st, msc);
cd.CommandType = CommandType.Text;
MySql.Data.MySqlClient.MySqlDataReader msdr = cd.ExecuteReader();
while(msdr.Read())
{
txt.Text = msdr[0].ToString();
}
Now, why is it returning the column name instead of the content of that column?
Lose the single quotes.
Change
"SELECT '" + txtchange.Text + "' "
to
"SELECT " + txtchange.Text + " "
In sql you can do it like this.
string query = "Execute("+"'SELECT " + txtchange.Text + " FROM mysql_9269_dbase." + pages.Text + "')";

Tables.Select on Unicode Characters

DataRow[] rows = myDataSet.Tables[0].Select("name = '" + _string + "'");
If _string contains UNICODE characters, do I need to prefix it with N like in TSQL?
DataRow[] rows = myDataSet.Tables[0].Select("name = N'" + _string + "'");
Thanks!
DataRow[] rows = myDatatable.Select("name = '" + _string + "'");
_string includes Myanmar Unicode string and wrong result returns(i.e. it returned all strings that include Myanmar Characters).
What's wrong with me?
I also tried
myDatatable.DefaultView.RowFilter("name = '" + _string + "'");
the same wrong result return.
I tested it. Adding an N-Prefix will throw an exception.
You don't need to put the N-Prefix even if you are working with Unicode characters.

Categories

Resources