I'm trying to do some Selects in a Datatable, but I am having some problems because I have values in some cells like this: 'COX-12-3SCS4CSCH
This value has ' and -
I tried to do this select but doesn't work:
string expression = "Nivel='" + lvfin + "' AND [Nivel " + lvfin + "]='" + codActual + "'";
DataRow[] results = DataTable.Select(expression);
lvfin contains for example 0 and codActual contains 'COX-12-3SCS4CSCH
And I get this error:
Missing operand after operator 'COX'
What is the problem here?
If your field name is Nivel 0 then you need to add that zero to the constant string "Nivel" and enclose the whole field name into square brackets to form the correct field name used in the first condition, then, if the value that you search contains a single quote, then you need to double it. All this is necessary to avoid confusing the parser when you use a single quote as delimiter for string values or your field names contains spaces.
So you should write (line by line for clarity but could be written in a single line):
string fieldName = "Nivel " + lvfin.ToString();
string searchValue = codActual.Replace("'", "''");
string expression = $"[{fieldName}]='{searchValue}'";
DataRow[] results = DataTable.Select(expression);
Related
I have the following query -
string query = "Insert into table(userId,companyID) values(" + userId + "," + SplitedLine[1] + ")";
writer.WriteLine(query);
When I am printing running this code then it is not printing the entire query in one column, rather it is breaking the query wherever there is a comma.
I tried this
How to write a value which contain comma to a CSV file in c#?
string query = "Insert into table(userId" +"\",\""+"companyID) values (" + userId + "\",\"" + SplitedLine[1] + ")";
writer.WriteLine(query);
But this is printing my insert commands in wrong format.
Please help.
Having tested this out, your simplest approach is to ensure that your query string is double quoted.
var query = $"\"Insert into table(userId,companyID values ({userId}, {SplitedLine[1]})\"";
I think the title of your question is ambiguous. You wanted to soround the values by quotation marks ("). But you made a mistake by escaping the " in the table part, it seams escaped " and not escaped was misked up.
Try to go with
string query = $"Insert into table(\"{userId}\",\"{companyID}\") values(\"{ userId}\",\"{SplitedLine[1]}\")";
I am trying to insert New Line after word car but it is not working with folowing solution
Char(13) - not working
Environment.NewLine - when i use this it works but appends '(' this char in sql rows like 'Car ( Rate:2CR'
\n\r - not working
Code:
cmd.Parameters.AddWithValue("#ColumnCar", Car + "char(13)" + "Rate:2CR";
//cmd.Parameters.AddWithValue("#ColumnCar", Car + "\n\r" + "Rate:2CR";
//cmd.Parameters.AddWithValue("#ColumnCar", Car + Environment.NewLine + "Rate:2CR";
cmd.ExecuteNonQuery();
Need output in sql table ColumnCar row value as follows:
Car
Rate:2cr
Note : here after Car there will be a newline and then Rate:2Cr will be added
With the LoC Car + "char(13)" + "Rate:2CR"; you will get a literal string "char(13)" between your 2 values, not a new line. If you want only a new line you can append "\n" or you can append the character equivalent (char)10 of new line.
Now what character or string actually represents a new line might depend on your environment including the collation you are using. In simple ascii/ansi this will work. It might not be the same for another collation. As #mhasan pointed out it could also be different depending on the O/S.
Using characters
const char carriageReturn = (char) 13; // see https://en.wikipedia.org/wiki/Carriage_return
const char newLine = (char) 10;
var car = "some car";
var toInsert = car + newLine + "Rate:2CR";
cmd.Parameters.AddWithValue("#ColumnCar", toInsert);
This would also work and produce the same result:
var toInsert = car + "\n" + "Rate:2CR";
Use combination of newline and carriage return characters i.e. char(13) + char(10) for inserting new line in windows OS system.
For MAC its \r char(13) , for Linux its \n i.e. char(10) but for windows its combination of both.
Try this code hope its working...
Make a string variable and store all value in variable..
ex: string abc=textbox1.text+" "+"Rate:2cr";
#ColumnCar=abc.tostring();
now put your code
cmd.Parameters.AddWithValue("#ColumnCar",datatype);
cmd.executenonquery();
The following code works fine with unicode fields in a MS SQL-Server 2016 DB :
string carString = $"Volvo{Environment.NewLine}Rate: 2CR";
SqlParameter parameter = new SqlParameter("#ColumnCar", carString);
command.Parameters.Add(parameter);
The '(' when you use Environment.NewLine must be another error somewhere else. What is Car in your code? A class instance? What does its ToString() expand to?
Don't use string1 + " " + string2 concatenation.
Use string.Format(), $"" - inline syntax (like above) or StringBuilder to build your strings.
I have a column in datatable where the columname is "last-updated" and I am trying to use the column name with filter like below
dv.RowFilter = " (last-updated >= #" + Convert.ToDateTime(dateTimePickerStart.Text).ToString("MM/dd/yyyy") + "# And Date <= #" + Convert.ToDateTime(dateTimePickerEnd.Text).ToString("MM/dd/yyyy") + "# ) ";
When I try to build I am getting
"Cannot find colum [last]".
I have tried to add single quote arrounding the column name but still not working.
I think - acts like an arithmetic operator in your case and this RowFilter thinks that last and updated as a two different columns and you try to calculate their differences.
Just wrap them with [] as [last-updated] in it should be fine.
Is it possible to compare values in some column with replacing some character from that column value with help of dynamic linq library
Regular Where statement
dbContext.TableName.Where("p=> p." + filterField+ ".Contains(\"" + filterValue+ "\")");
What i need
dbContext.TableName.Where("p=> p." + filterField+".Replace(\"*\",\"\")"+ ".Contains(\"" + filterValue+ "\")");
which will evaluate to
dbContext.TableName.Where(p=> p.filterField.Replace("*","").Contains("filterValue"));
I am getting exception when i am trying to replace double quotes - Similar to this.
I thought that "bill" + "john" + null == billjohn, but in this example of mine it seems to be evaluating to null:
var clients = from client in taxPortalService.Client()
select new ClientViewModel
{
ResidentialAddressLine1 = client.RESADDRESSLINE1,
ResidentialAddressLine2 = client.RESADDRESSLINE2,
ResidentialAddressLine3 = client.RESADDRESSLINE3,
ResidentialAddressLine4 = client.RESADDRESSLINE4,
ResidentialPostalCode = client.RESPOSTCODE,
ResidentialCountry = client.RESCOUNTRY,
IAResidentialAddress = client.RESADDRESSLINE1 + ", " + client.RESADDRESSLINE2 + ", " + client.RESADDRESSLINE3 + ", " + client.RESADDRESSLINE4 + ", " + client.RESPOSTCODE + ", " + client.RESCOUNTRY
};
Am I missing something obvious here?
I'm guessing this is using LINQ-to-SQL or EF as a backend, and it is generating SQL. Well, in TSQL a null concatenated with anything is (by default): null. Perhaps try:
(row.Foo ?? "") + ", " + (row.Bar ?? "") + ...
or easier: get the data as values into memory first, then do compositions.
In C#, or rather in .NET, you're right, "bill" + "john" + null gives you "billjohn".
In SQL, 'bill' + 'john' + null gives you null.
Using LINQ to Entities translates your C# to SQL, and subtle differences such as this aren't always preserved.
You can use the more verbose
(client.RESADDRESSLINE1 ?? "") + ", " + (client.RESADDRESSLINE2 ?? "") + ", " + ...
to make sure you only concatenate non-null strings, which won't have this problem.
Assuming SQL-Server as rdbms, a quick test reveals:
select 'A' + NULL; // NULL
Demo
MSDN
The + (String Concatenation) operator behaves differently when it
works with an empty, zero-length string than when it works with NULL,
or unknown values. A zero-length character string can be specified as
two single quotation marks without any characters inside the quotation
marks. A zero-length binary string can be specified as 0x without any
byte values specified in the hexadecimal constant. Concatenating a
zero-length string always concatenates the two specified strings. When
you work with strings with a null value, the result of the
concatenation depends on the session settings. Just like arithmetic
operations that are performed on null values, when a null value is
added to a known value the result is typically an unknown value, a
string concatenation operation that is performed with a null value
should also produce a null result. However, you can change this
behavior by changing the setting of CONCAT_NULL_YIELDS_NULL for the
current session. For more information, see SET CONCAT_NULL_YIELDS_NULL
(Transact-SQL). If the result of the concatenation of strings exceeds
the limit of 8,000 bytes, the result is truncated. However, if at
least one of the strings concatenated is a large value type,
truncation does not occur.