I want the user to be able to choose from a dropdown Combobox listing some of the fields of the database, then below enter a search term and all then all the results that meet the query be displayed in the dbgrid. I'm not sure how to link the current value of the ComboBox into the sql statement. I tried using this
begin
with ADOQuery do begin
Close;
SQL.Clear;
SQL.Add ('SELECT * FROM List WHERE combobox1.text =' + QuotedStr (Asearchterm.Text));
Open;
And it doesn't work. The error i'm getting is "The parameter combobox1.text has no default value". Any ideas?
If you're wanting to use the combobox1 text value as part of the sql statement, you'd set up the sql string along the lines of
'SELECT * FROM List WHERE [' + combobox1.text + '] = ''' + QuotedStr(Asearchterm.Text) + ''''
is probably what you're looking for. I added the extra quotes around the QuotedStr because I'm guessing that the filter is not always going to be numeric values. This will work for numeric as well as non-numeric values.
instead of 'combobox1.text' you have to put actual column name that you are looking for. And you can use LIKE keyword and some wildcards. something like:
SELECT * FROM 'table WHERE 'column' LIKE '%YOUR_SEARCH_TEXT%';
That was for a search...if you want to find exact string then you have to use = operator instead of LIKE
More info here
Related
To Increase Speed of search in the database, i want to do something like this:
If field TheFieldName (without any space in it) was equal with test then show the record(s)
how can i do it?
This did'nt work for me:
"SELECT * FROM TheTableName WHERE REPLACE(TheFieldName, ' ', '')=test"
Error: Undefined function 'REPLACE' in expression
It seems unlikely to me that replace() is not known in SQL Server (or almost any other database). But, check to be sure you are using the database you think you are.
Your query, as written, does have an error -- because you seem to want test as a string. Does the query really look like this:
SELECT *
FROM TheTableName
WHERE REPLACE(TheFieldName, ' ', '') = 'test';
Note the quotes around 'test'.
This should work.
"SELECT * FROM TheTableName WHERE rtrim(ltrim(TheFieldName))=test"
there. I am trying to search for a string contained in any column of a sql table by adding all the Fieldnames to the WHERE clause using a for loop. Also I use parameters to protect against SQL injection. But when I run I get an error like this:
Unspecified error
How can this be fixed and what is the problem (Not necessarily in that order). Here is my code. I am running Delphi 7
procedure TfrmView.edtSearchChange(Sender: TObject);
var
i, i2: integer;
obj: TEdit;
QueryText: string;
begin
obj:= Sender as TEdit;
with dmInfo do
begin
qryInfo.SQL.Clear;
qryInfo.SQL.Add('SELECT * FROM ' + tableName);
qryInfo.Open;
tblInfo.SQL.Clear;
tblInfo.SQL.Add('SELECT * FROM ' + tableName);
tblInfo.SQL.Add('WHERE (' + qryInfo.Fields[0].FieldName + ' LIKE :SQuery0)');
QueryText:= '%' + obj.Text + '%';
tblInfo.Parameters.ParamByName('SQuery0').Value:= QueryText;
ShowMessage(QueryText);
ShowMessage(tblInfo.Parameters.ParamByName('SQuery0').Value);
for i:= 1 to qryInfo.FieldCount - 1 do
begin
tblInfo.SQL.Add(' OR (' + qryInfo.Fields[i].FieldName + ' LIKE :SQuery' + IntToStr(i) + ')');
tblInfo.Parameters.ParamByName('SQuery' + IntToStr(i)).Value:= '%' + obj.Text + '%';
end;
tblInfo.Open;
end;
The whole code makes no sense.
You let the code run every time you change a letter.
run by an onChange event
five input/letter to the edtSearch input field means the code is executed five times without interruption immediately
If you delete all content in the edtSearch input field at once,
which is also a change event.
This time it runs with an empty edtSearch.text
How can you expect that this works without exceptions
You open each time two tables without to close them before.
you are using a variable, which suggests that this event is also
connected to other TEdits.
obj: TEdit;
obj:= Sender as TEdit;
You clear the SQL on an open table.
you have two tables the first one does nothing more than SQL.clear
and open
You're using fields from first table and create the SQL for second table
Even if both tables are the same, it makes no sense to use the fields
from the first table.
It is confusing, misleading and unnecessary.
First of all remove the code out of the onChange event
What you want to do with this code
to search for values on all fields from the tblInfo
can be done without the first tabel qryInfo
you do not need to increment the params.
Do not create the params all the time from SQuery1 to maybe SQuery100
if you only use one param (the search value is always the same)
You can set all params with a single use tblInfo.Parameters.ParamByName() before the tblInfo.Open
but NOT in the loop.
This will replace all params :SQuery all at once with the value
SQL.Text :
SELECT * FROM tableName
WHERE (IDmember LIKE :SQuery)
OR (memberName LIKE :SQuery)
OR (petName LIKE :SQuery)
OR (Address LIKE :SQuery)
Maximum Length Of An SQL Statement
Is different from database to database
How many OR clauses can I use in a single WHERE condition in MySql query?
I know there was a limit in the past.
But now the experts knowledge is different
only one of the opinions
The truth is that it's limited to the resources available on the
database, the size of the data set in question, the indexes being
addressed (or lack thereof) and the complexity of each clause.
If your goal is to find a person record that meets multiple criteria,
I am willing to bet you won't run in to a limit. You could easy OR
condition with 20 to 30 conditions and no user is going to provide
more that that / person records won't have more than one that meets
that many conditions.
In my report query I have a where clause that needs to be replaced dynamically based on the data chosen in the front end.
The query is something like :
where ?=?
I already have a code to replace the value - I created report parameter and linked to the value ? in the query.
Example:
where name=?
Any value of name that comes from front end replaces the ? in the where clause - this works fine.
But now I need to replace the entire clause (where ?=?). Should I create two parameters and link them to both the '?' ?
No, unfortunately most database engines do not allow to use a query parameter for handling a dynamic column name. This is for security considerations.
So you need to keep an arbitrary column name in the query:
where name=?
And then in "beforeOpen" script of the dataset replace 'name' with a report parameter value:
this.queryText=this.queryText.replace("name",params["myparameter"].value);
To prevent SQLIA i recommend to test the value of the parameter in this script. There are many ways to do this but a white list is the strongest test, for example:
var column=params["myparameter"].value;
if (column=="name" || column=="id" || column=="account" || column=="mycolumnname"){
this.queryText=this.queryText.replace("name",column);
}
In addition to Dominique's answer and your comment, then you'll just need a slightly more advanced logic.
For example, you could name your dynamic column-name-value pairs (column1, value1), (column2, value2) and so on. In the static text of the query, make sure to have bind variables for value1, value2 and so on (for example, with Oracle SQL, using the syntax
with params as (
select :value1 as value1,
:value2 as value2 ...
from dual
)
select ...
from params, my_table
where 1=1
and ... static conditions....
Then, in the beforeOpen script, append conditions to the query text in a loop as needed (the loop left as an exercise to the reader, and don't forget checking the column names for security reasons!):
this.queryText += " and " + column_name[i] + "= params.value" + i;
This way you can still use bind variables for the comparison values.
Using Sql Server 2012 I want to query a table to only fetch rows where certain columns are not null or don't contain an empty string.
The columns I need to check for null and ' ' all start with either col_as or col_m followed by two digits.
At the moment I write where col_as01 is not null or ....
which becomes difficult to maintain due to the quantity of columns I have to check.
Is there a more elegant way to do this? Some kind of looping?
I also use ISNULL(NULLIF([col_as01], ''), Null) AS [col_as01] in the select stmt to get rid of the empty string values.
thank you for your help.
You should fill in the blanks.
select
#myWhereString =stuff((select 'or isnull('+COLUMN_NAME+','''') = '''' ' as [text()]
from Primebet.INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'YourTable'
and (column_name like 'col_as%'
or
column_name like 'col_m%')
for xml path('')),1,3,'')
set #myWhereString ='rest of your query'+ #myWhereString
exec executesql with your query
You can use something like this
WHERE DATALENGTH(col_as01) > 0
That will implicitly exclude null values, and the length greater 0 will guarantee you to retrieve non empty strings.
PS: You could also use LEN instead of DATALENGTH but that will trim spaces in your string at the beginning and end so you would not get values that only contain spaces then.
Simple as this:
WHERE col_as01 > ''
I would like to build one sql query in that one of my filed of form should not contain common names (maintained list of words in separate table) and i am passing value of that filed as parameter and want to check that it shouldn't contain any common name from that table.
How can i achieve that using sql query?
Note : if common name is 'abc' and i am passing parameter as '!abc123' since it contains that word query should return false.
Thanks in advance.
Try something like (Untested Query):
SELECT CommonName
FROM CommonNamesTable
WHERE CommonName like '%NameToTest%'
OR CONTAINS(NameToTest, CommonName);
Basically you need the string match options:
Take a look at options of CONTAINS and read about Queries with full text search
Is this what you're looking for?
SELECT (COUNT(*) == 0) FROM tablewithcommonwords
WHERE wordfromform LIKE CONCAT('%', wordcolumnnfromcommonwordstable, '%');
Try this:
IF NOT EXISTS(SELECT word FROM CommonWord WHERE #yourparam
LIKE '%' + word + '%')
BEGIN
RETURN 1
END
ELSE
BEGIN
Return 0
END
This works if the #yourParam is contained in any word or name, what you do not want to use. It only returns 1 if it is not contained by any row in the table.
I worte this sentence only on this way (you can use a simple Exists instead of NOT Exists), because may you want to extend the functionality in the true part.
if exists (select * from reservedwords where #parameter like '%'+word + '%')
select 0
else
select 1
I would like to suggest that You have to use keypress Event in Your TextBox and then Handle your Code after Each character enter in your TextBox.