How to use this expression correctly with a space in the select query?
string expression = "'Loan' 'ID'='" + ViewState["name"];
DataRow[] sign = ((DataTable)ViewState["customer"]).Select(expression);
I get:
Exception has Operand is missing after ID operator.
This will work and return datarow array.
DataRow[] sign = ((DataTable)ViewState["customer"]).Select("[Loan ID]='" + id_here +"'");
Related
This question already has answers here:
IN Operator in OLEDB
(2 answers)
Closed 1 year ago.
I have some data like name,firstname,surname,std,Rollno.
Using C#, I want to convert this into
('name', 'surname', 'std', 'Rollno')
so that I can use this this data to query into the SQL/MySQL DB like -
SELECT *
FROM Table1
WHERE UserCommunicationId IN ('name', 'surname', 'std', 'Rollno');
Instead of
SELECT *
FROM Table1
WHERE UserCommunicationId IN ('name,surname,std,Rollno');
You can try below below logic
public static class SQLQueryExtensions
{
public static string ColumnFormat(this String str)
{
return "(" + //Include first parenthesis
string.Join(", ", str.Split().Select(x => $"'{x}'")) //Add single quote to each column
+ ")"; //Include last parenthesis
}
}
You can do it in one line as well,
var inputStr = "name,firstname,surname,std,Rollno";
var result = "(" + string.Join(", ", inputStr.Split().Select(x => $"'{x}'")) + ")";
Try Online
Use blow logic, will solve your problem.
string inputStr = "name,firstname,surname,std,Rollno";
string result = string.Join(",", inputStr.Split(',').Select(x => string.Format("'{0}'", x)).ToList());
Output = 'name','firstname','surname','std','Rollno'
One approach I can come up is that:
Set the whole string into query as a parameter.
Split it in a WITH query.
LEFT JOIN it in the main query.
NOT NULL to check if there's any hit.
I've wrote an example below, but I am Oracle user so I am not sure if these syntax are right, not even tested, just googled around. Only take it as an reference to the explanation of the idea.
WITH RECURSIVE targets (stringBuffer, word) AS (
SELECT
#Parameter
,NULL
UNION ALL
SELECT
SUBSTRING(stringBuffer, LEAST(LENGTH(SUBSTRING_INDEX(stringBuffer, ',', 1) + 1, LENGTH(stringBuffer)))
,SUBSTRING_INDEX(stringBuffer, ',', 1)
WHERE LENGTH(word) > 0
OR LENGTH(stringBuffer) > 0 -- I am not really sure about these
)
SELECT *
FROM Table1
LEFT JOIN targets ON targets.word = Table1.UserCommunicationId
WHERE targets.word IS NOT NULL;
Then, in C#, set Parameter for your query command in string like this
string s = "name,firstname,surname,std,Rollno";
Edit:
Or, simply:
SELECT *
FROM Table1
WHERE REGEXP_LIKE(UserCommunicationId, #Parameter)
;
While setting the Parameter in C# as:
string s = "name|firstname|surname|std|Rollno";
Notice that if the keywords can be input by user, you still have the problem where user may enter .+ and it responds every data to them as long as there's no other condition added.
But personally, I think there's a potential issue in your design if you really need an unknown length of IN-CLAUSE in your query. If keywords that can be applied are limited in number, you can, rough but it's my team's current criteria, concat the WHERE section keyword by keyword in C#.
Is my if condition statement right? I'm trying to read the value of my table column that if it's contain a value of 1 then it will get the value of the book I'm searching.
The code doesn't have any errors. It compiles.
string sql = "SELECT * FROM tbladdbook WHERE fBarcodeNo LIKE '" + txtBARCODE.Text.Trim() + "%'";
cfgotcall.engageQuery(sql);
if (cfgotcall.tbl.Rows[0]["fCurrentCopies"].ToString().Equals(1))
{
txtTITLE.Text = cfgotcall.tbl.Rows[0][1].ToString();
}
else
{
MessageBox.Show("Book already borrowed.");
}
If statement does not work because you compare string vs int. So it always return false.
if (cfgotcall.tbl.Rows[0]["fCurrentCopies"].ToString().Equals(1))
cfgotcall.tbl.Rows[0]["fCurrentCopies"].ToString() => It is a string. Maybe it is "1"
1 is an integer (int)
=> To make it work correctly, you should change 1 (int) to "1" (string) like this:
if (cfgotcall.tbl.Rows[0]["fCurrentCopies"].ToString().Equals("1"))
Try this. It assumes that the database field type is a numeric field. As a side note, using SELECT * is bad. You should only retrieve what you need.
Do you want to check result == 1 or result > 0? In this scenario, where a library might have multiple books, I'd suggest you want to check > 0
string sql = "SELECT * FROM tbladdbook WHERE fBarcodeNo LIKE '" + txtBARCODE.Text.Trim() + "%'";
cfgotcall.engageQuery(sql);
var result = cfgotcall.tbl.Rows[0]["fCurrentCopies"];
if (DBNull.Value.Equals(result) || result == null) { result = 0; }
if ((int)result == 1)
{
txtTITLE.Text = cfgotcall.tbl.Rows[0][1].ToString();
}
else
{
MessageBox.Show("Book already borrowed.");
}
As a side note, everything in C# inherits from the "object" type. .Equals( ) accepts an object, not a string or an integer, etc. This is why you don't get a compliation error.
I was writing a method in C# using ADO.NET Entity Framework for MySQL. I was making a function where when the function is called, I specify the column I'm selecting, kind of like this:
public string GetColumn(string whereValue, string column)
{
xxxEntities data = new xxxEntities();
lock (lockObject)
{
var result = data.employees.SqlQuery("SELECT `" + column + "` FROM `employees` WHERE `Code` = '" + code + "'");
return result.ToListAsync().Result[0].????; // I want to get the column in the parameters
}
}
Thanks, any help would be appreciated.
Let's assume that your target column is a string, for a moment. Then your syntax would be this:
// I've parameterized the parameterizable part of your query
var result = data
.employees
.SqlQuery<string>("SELECT `" + column + "` FROM `employees` WHERE `Code` = #p0", code);
return result.ToListAsync().Result[0]; // Result[0] is a string
If your target column were an integer, that first line would be:
var result = data
.employees
.SqlQuery<int>("SELECT `" + column + "` FROM `employees` WHERE `Code` = #p0", code);
The program will have no idea what type result needs to be, so you need to tell it by supplying a type parameter to the SqlQuery method.
If column can have varying types, you have a bit of a problem, because there is no way for C# to intuit what the property type is going to be. You might have to use some special logic.
Another way to do this, by the way, that doesn't involve building custom SQL, would be to use the employee object for querying, but use Reflection to access the desired property:
// Warning: this is being done from memory.
var result = data.employees
.Where(e => Code == code);
// Assuming the property is a string:
return result
.Select(e => (string) typeof(employee).GetProperty(column).GetValue(e))
.ToListAsync();
This is my code
var compainNames = (from row in DTgraph.AsEnumerable()
group row by row.Field<string>("Campaign") into grp
select new
{
CampaignName = grp.Key
}).ToList();
var dataForOneCampaint = DTgraph.Select("Campaign = " + compainNames[i].ToString()).ToList();
where DTgraph is a datatable.
I got this exception:
Cannot interpret token '{' at position 12.
Could you help please?
I debug and i can see that compainNames has 3 strings
the exception in this line
var dataForOneCampaint = DTgraph.Select("Campaign = " + compainNames[i].ToString()).ToList();
DataTable.Select method use the same rules with DataColumn.Expression property for creating filters.
From it's documentation;
User-Defined Values
User-defined values may be used within expressions to be compared with
column values. String values should be enclosed within single
quotation marks (and each single quotation character in a string value
has to be escaped by prepending it with another single quotation
character).
I believe you can use;
var dataForOneCampaint = DTgraph
.Select("Campaign = '" + compainNames[i].ToString() + "'")
.ToList();
Or use String.Format as Felipe mentioned.
Try using the ' char between the string, for sample:
var dataForOneCampaint = DTgraph
.Select(string.Format("Campaign = '{0}'", compainNames[i].ToString()))
.ToList();
I have datatable and there two column which is type of string and I want to make addition of that two columns data for another column how can I do that ?
My column name contains special character and I have used "[" "]" to escaping special character and my columns are type of decimal I am doing
TableExtractedFromFile.Columns[TOT BROK(Rs)].Expression =
"'"+"["+SER TAX(Rs)+"]"+"'+'"+"["+STT(Rs)+"]"+"'";
But The column TOT BROK(Rs) contains the contenation of values of columns SER TAX(Rs) and STT(Rs).But I want the sum of the values of these two columns.
EDIT
It works. But If I do like there is three columns A,B and C. Now if do I table.columns["A"].expression = "A+B+C"; then it gives error like Cannot set Expression property due to circular reference in the expression. then what is the solution of that ?
Use this:
dt.Columns.Add("fullname", typeof(string));
dt.Columns["fullname"].Expression = "lastname + ', ' + firstname";
For adding of value(Total,Amount and Surcharge are your existing columns, and are type string, you need to put CONVERT function in your column names so they will be casted to decimal(System.Decimal), if int use System.Int32 or System.Int64, etc):
dt.Columns["Total"].Expression =
"CONVERT(Amount,System.Decimal) + CONVERT(Surcharge,System.Decimal)";
[EDIT]
Just do it in your backend:
select *, CONVERT(SERTAX(Rs), DECIMAL)
+ CONVERT(STT(Rs), DECIMAL) AS brokerage
from tbl
If you have control in your database, modify the SERTAX and STT function so it can return decimal/currency/int, not string.
Then in your front-end, do this:
dt.ColumnChanging += (ds, de) =>
{
if (de.Column.ColumnName == "Rs")
{
decimal serTaxResult = (decimal)new SqlCommand("select SERTAX(" + de.ProposedValue + ")").ExecuteScalar();
decimal sttResult = (decimal)new SqlCommand("select STT(" + de.ProposedValue + ")").ExecuteScalar();
// if your SERTAX AND STT really return string, use this:
// decimal serTaxResult = decimal.Parse( (string) new SqlCommand("select SERTAX(" + de.ProposedValue + ")").ExecuteScalar() );
// decimal sttResult = decimal.Parse( (string) new SqlCommand("select STT(" + de.ProposedValue + ")").ExecuteScalar() );
de.Row["brokerage"] = serTaxResult + sttResult;
}
};
[EDIT]
If all your columns are string type, you have to enclosed each of them with their own CONVERTs.
.Expression = string.Format("CONVERT({0},System.String)",
"CONVERT(" + serviceTaxClmnInCNote + ", System.Int32)"
+ " + "
+ "CONVERT(" + STTClmnInCNote + ", System.Int32)"
);
Just change the System.Int32 to System.Decimal if the serviceTax and STT are money type.
Extract the data from te two columns and call the string concat function. Refer the following link
http://www.1keydata.com/sql/sql-concatenate.html