Click here to Skip to main content
15,891,976 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I have a doubt about a sql query that i need if anyone can help thanks in advance.

I want to query a products database created in MS Acess through an application in C #. I need to consult the database looking for the product by reference, this reference may contain various names and spaces, for example: "ABC FFF HHH XXXXXXXX" and i want for example to introduce in textbox part of a string to search, for example: "HHH" and the query will return me all references containing "HHH" regardless of being at the beginning, middle or end of the reference.

The query that i have does not return anything:

SQL
Select * from product where product_ref like '% + TextBox_ref.Text +%';


What should i change in the query to get all the references containing the characters entered in the TextBox regardless of spaces that the reference may have in the database?

Thanks,

What I have tried:

SQL
Select * from product where product_ref like '% + TextBox_ref.Text +%';
Posted
Updated 18-Oct-16 17:17pm
v2
Comments
[no name] 18-Oct-16 19:31pm    
You should learn how string concatenation works.
"Select * from product where product_ref like '%" + TextBox_ref.Text + "%'";

1 solution

As already pointed out, you should concatenate the value from the text box to separate strings, for example
C#
Select * from product where product_ref like '%'" + TextBox_ref.Text + "'%'

However, what you really should do is to use paramters, OleDbParameter Class (System.Data.OleDb)[^] in this case. The query text would then look like
C#
Select * from product where product_ref like '%' + @searchString + '%'

Now you would add a parameter for the OleDbCommand and set it's value. This would keep you safe from for example SQL injections.

Not sure if you wanted also to find rows having HHH even if the data in the database would be H HH. If that is the case, you can use REPLACE function to remove whitespace. For example
C#
Select * from product where REPLACE(product_ref, ' ', '') like '%' + @searchString + '%'
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900