Trying to Count data with the same suffix in a table - sql-server

I have the code below and I'm trying to count data with the suffix "Fertilizer" and "pesticide" from a table in my SQL server database. The code is not working, what can be the problem
private string GetFarmInputCount()
{
string ret = "_ _";
string query = "SELECT Count(*) FROM Loan WHERE Name LIKE 'Fertilizer' AND 'Pesticide'";
DataTable dt = QueryDatabase(query);
foreach(DataRow row in dt.Rows)
{
ret = row[0].ToString();
}
return ret;
}

You need to add wildcards to the strings you are trying to match so that SQL Server knows where to match additional characters. In this case, the wildcard is %, and you want to match cases where your strings are suffixes, so you need to put the wildcard at the beginning. Your query then should look like this:
SELECT Count(*) FROM Loan WHERE Name LIKE '%Fertilizer' OR '%Pesticide'"
You can find more information in the Microsoft docs on how pattern matching with LIKE works, including other types of wildcards you can use.

Related

VB.NET, SQL Server and list of dates

I have a query that takes as a parameter a list of dates. In VB.NET the dates are in a string ArrayList and I am using the String.Join() method to get them in a comma delimited list. The problem is when I do that double quotes are put at the start and end of the string and SQL complains about that (I think; see below). How can I get a list of date from a string ArrayList without the quote.
My arraylist contains these values:
'2020-08-30'
'2020-08-27'
'2020-09-28'
'2020-09-09'
'2020-08-31'
'2020-08-29'
when I join them using String.Join(",", sDates) I get the following:
"'2020-08-30','2020-08-27','2020-09-28','2020-09-09','2020-08-31','2020-08-29'"
and when I use that in a parameter query it gets rejected.
comm.Parameters.AddWithValue("#dates", String.Join(",", sDates))
sql contains the following"
...where pj.ProjectName =#projectname And tcd.Date in (#dates)
Exact error I get is
System.Data.SqlClient.SqlException
HResult=0x80131904
Message=Incorrect syntax near ','.
Source=.Net SqlClient Data Provider
Any advice?
This error message:
Incorrect syntax near ','
Is not caused by the way you've done your IN. It is caused by something else, such as a misplaced comma in a select block:
SELECT , a FROM x
^
The way you've done your IN won't work either, because it's conceptually the same as writing this:
SELECT * FROM table WHERE dateColumn IN ('''2000-01-01'',''2000-02-01''')
There is no such date with a string value of '2000-01-01','2000-02-01'.
If you want to use IN in the style you're attempting here, you have to add a parameter per date value and set it up accordingly:
sqlCommand.CommandText = "SELECT * FROM table WHERE dateCol IN("
Dim p = 0
For Each d as DateTime in MyDateList
sqlCommand.CommandText &= "#p" & i & "," 'concat param placeholder on
sqlCommand.Parameters.AddWithValue("#p" & i, d)
i += 1
Next d
sqlCommand.CommandText = sqlCommand.CommandText.TrimEnd(","c) & ")" 'get rid of trailing comma and close the IN brackets
This will generate an sql like
SELECT * FROM table WHERE dateCol IN (#p0,#p1,#p2)
with 3 parameters, and a populated parameters collection. You've already been pointed to Joel's blog about AddWithValue, so I won't repeat it.. But i did want to say that the way you've presented your question implies you have a list of strings, not datetimes. You should definitely make sure your list has DateTimes in, and your db column should be a date based type, not a string based type

Dapper, SqlBuilder extension and Order By descending

I am trying to build a simple query that retrieves data in descending order using Dapper. The database is MySql if that's important.
This is the code I used:
var builder = new SqlBuilder();
var sql = #$"SELECT * FROM table t /**orderby**/ LIMIT #paramSkip, #paramTake";
var template = builder.AddTemplate(sql);
builder.OrderBy("#paramOrderBy DESC", parameters: new
{
paramOrderBy = orderBy,
});
// Limit
builder.AddParameters(parameters: new
{
paramSkip = skip,
paramTake = take
});
return Connection.QueryAsync<TableModel>(
template.RawSql, template.Parameters,
transaction: Transaction
);
This always returns data in ascending order. DESC is just ignored. I tried using the DESC keyword in the query or as parameter but the result was the same.
Only thing that worked was putting order parameters and DESC keyword in query itself (by string interpolation)
(Edit: Typos and text simplification)
You need your query to look something like this:
... ORDER BY <Column name> DESC ...
A column name cannot be parameterized, so you need to insert it into the query something like this:
builder.OrderBy($"{orderBy} DESC");
If your orderBy originates from the user in any way, be sure to sanitize it first to prevent SQL injection. You could - for instance - keep a list of valid column names and validate against it.

how to get approximate searching results in sql server 2014

How to write sql procedure to get matching results while searching for string values.It should search by the similarity of the characters entered by user. For instance Ahmmed, Ahmad, Ahmmad or Mohammad, Mohammed, Mohamad etc should display all similar names while executing search.
Any help would be highly appreciated.
Thanks in advance.
Well I guess you need AI for that but, you can use the like keyword to do wildcards.
e.g.
$search_string = 'Ahm'; //or Moha
$query = SELECT column FROM tableName WHERE column LIKE '$search_string%'; //starts with the $search_string
or
$query = SELECT column FROM tableName WHERE column LIKE '%$search_string'; //ends with the $search_string
or
$query = SELECT column FROM tableName WHERE column LIKE '%$search_string%'; //starts and/or ends with the $search_string
take note of the %

c++ builder: getting values via ADOQuery using SELECT

The question is as for delphi coders as for c++ builder coders, cuz I'm using the same components.
I'm trying to fill labels on the form by the data from database. I do a SELECT query via TADOQuery. But when I try to get a result, I always get an error like "ADOQuery1: Field 'count' not found".
'id' passed to the function is an autoincrement field value, which is EXACTLY exists in database (it was got via DBLookupComboBox). Also, executing the query manually to show result in DBGrid is successfull.
Querying without parameters and writing 'id' value to query string fails too.
What's the problem? Here's the code.
void TSellForm::LoadData(int id) {
TADOQuery* q = DataModule1->ADOQuery1;
q->Active = false;
try
{
q->SQL->Text = "select * from drugs where(id=:id)";
q->Parameters->ParamByName("id")->Value = IntToStr(id);
q->ExecSQL();
this->LabelAvail->Caption = q->FieldByName("count")->Value;
}
catch (Exception* e) {
MessageBox(NULL, PChar(WideString(e->Message)),
L"Exception", MB_OK|MB_ICONWARNING);
}
q->SQL->Clear();
}
ExecSQL is only used for SQL statements that don't return a recordset, and to determine the results you use RowsAffected.
For SELECT statements (which return a recordset), you use Open or set Active to true.
Also, count is a reserved word in most SQL dialects (as in SELECT Count(*) FROM ..., so if you have a column with that name you're going to need to escape it, typically by using either [] or double-quotes around it or by aliasing it in the SELECT itself.
ADOQuery1->Close();
ADOQuery1->SQL->Text= "SELECT * FROM reportTble WHERE (firstName =:firstName) " ;
ADOQuery1->Parameters->ParamByName("firstName")->Value = textBox->Text ;
ADOQuery1->Open();
This is how you can use ADOQuery

Replace substring of database record with another substring in Matlab

I know how to update a record and replace a sub string in another string:
update(conn,'tableName',{'columnName'},{'value'},'where columName=xx') %update record in database
modifiedStr = strrep(origStr, oldSubstr, newSubstr) %replaces substring with new string in another string.
Now i want to mix these two and change substring of a record in the database. How can we do that? I want a query to do this. Can we mix the two by any chance?
You don't need the {} brackets if you deal with only one column.
If you have a the column name and hold it in a variable columnName, you can try something similar:
columnName = 'product_id';
whereClause = ['where ',columName,'=',origStr];
modifiedStr = strrep(origStr, oldSubstr, newSubstr);
update(conn,'tableName',columnName,modifiedStr,whereClause);
Of course you don't need to use the variables you can just replace the desired string inside the update function, but I did it for clarification.

Resources