-1

I couldn't find answer on my problem so I had to rise new question. Namely I would like to ask you how to use LIKE +value from textbox+ with % - wildcards (missing letters) but for two or more fields. When I use below code for one field it's working (and I can search in my DB E.G. all FirstNames which starts from "A"):

"SELECT * FROM customer WHERE FirstName LIKE '"+TextBox1.Text + '%'+ "'";

But when I trying to use it for two fields, It's not working,(and I can't search in my DB e.g. any FirstNames or LastNames which starts from "R". I didn't get any errors. Just nothing is happen):

"SELECT * FROM customer WHERE FirstName LIKE '"+TextBox1.Text + '%'+ "' OR LastName LIKE '" +TextBox2.Text + '%'+"'";

Thank you in advance for any advice.

Adrian
  • 31
  • 2
  • 6
    Please don't insert user input directly into your query, use parameterized queries instead. Your code is open to [SQL Injection](http://www.bobby-tables.com/)! – René Vogt Feb 07 '17 at 11:53
  • What does the generated SQL come out as? – Rowland Shaw Feb 07 '17 at 11:53
  • 3
    Define *It's not working*. – Patrick Hofman Feb 07 '17 at 11:54
  • 2
    What means "nothing happens"? does it freeze? or do you get an empty result set? Did you try to run the query in SQL Management Studio or any other DB interface to check if it works? Maybe your input data was already incorrect (or you tricked yourself already with sql injection). – René Vogt Feb 07 '17 at 11:56
  • @RenéVogt, You are absolutely right, I will change it, but it is only for my test. – Adrian Feb 07 '17 at 12:33
  • @RowlandShaw noting is comming out, I have empty table with results. – Adrian Feb 07 '17 at 12:46
  • Then it's probably your query was constructed properly and you just overlooked you have no suitable data. Just fill them in and your issue should be solved. Anyway I'd think about improving your scripts as described in answers. In case your issue would be solved feel free to mark some answer as helpful so it's visible you already solved original problem. – Jaroslav Kadlec Feb 07 '17 at 14:48

4 Answers4

3

You should not create your queries by string concatenation otherwise you're exposing your application to SQL Injection. Better use command with parameters - that will also help you to not need think much about string escaping which is probably causing your current issue.

using (SqlCommand cmd = new SqlCommand())
using (SqlConnection conn = new SqlConnection("connectionString"))
{
       cmd.CommandText = "SELECT * FROM customer WHERE FirstName LIKE @first OR LastName LIKE @second";
       cmd.Parameters.Add(new SqlParameter("first", SqlDbType.NVarChar, 255).Value = "%" + TextBox1.Text + "%");
       cmd.Parameters.Add(new SqlParameter("second", SqlDbType.NVarChar, 255).Value = "%" + TextBox2.Text + "%");
       // todo: execute
}

You could also verify that query you're currently creating in your app (just set breakpoint before execution or simply log it somewhere to file f.e.) is returning results you'd expect in case you'd execute it directly on server. That could help you examine some more issues.

Jaroslav Kadlec
  • 2,505
  • 4
  • 32
  • 43
0

I see how @Jaroslav Kadlec is doing it, he is not wrong but he has one problem. He is using the depricated method. To add paramaters there is an new method:

using (SqlConnection conn = new SqlConnection("connectionString")){
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
    cmd.CommandText = "SELECT * FROM customer WHERE FirstName LIKE @first OR LastName LIKE @second";
    cmd.Parameters.AddWithValue("@first", TextBox1.Text + "%");
    cmd.Parameters.AddWithValue("@second", TextBox2.Text + "%");
}}
Joris van Roy
  • 183
  • 1
  • 1
  • 12
  • 2
    `AddWithValue` has it's own limitations. Creating the `SqlParameter`s with explicit typing and sizing gives predictable results – Rowland Shaw Feb 07 '17 at 12:48
  • @RowlandShaw +1. As addition AddWithValue doesn't allow you to specify size constraint for nvarchar types - look at usage in my answer. In case you do so, you're doing kind service for SQL Server. – Jaroslav Kadlec Feb 07 '17 at 14:28
0

If you have a dynamic number of tokens, one convoluted way to do your task is by defining a temporary table and join with it:

using (var conn = new SqlConnection(connectionStr))
{
    conn.Open();
    using (var cmd = conn.CreateCommand())
    {
        var querySb = new StringBuilder(@"
            CREATE TABLE #temp (Token NVARCHAR(20) NOT NULL)");

        //tokensArray will contain texts from your text boxes
        for (int i = 0; i < tokensArray.Length; i ++)
        {
            querySb.Append($"INSERT INTO #temp VALUES(@p{i})");

            // parameterized query, to protect against SQL injection (input is coming from user)
            cmd.Parameters.AddWithValue($"@p{i}", $"%{token}%");
        }

        cmd.CommandType = CommandType.Text;
        cmd.CommandText = querySb.ToString();

        querySb.Append(@"; 
SELECT C.* 
FROM customer C 
    JOIN #temp T ON C.FirstName LIKE T.Token";

        // execute stuff
    }
}

You can also consider sending tokens in a concatenated string and use a stored procedure to split them and make the filtering in T-SQL.

Credit goes to this answer.

Community
  • 1
  • 1
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
  • Would be better to use it in this way `cmd.Parameters.Add(new SqlParameter($"@p{i}", SqlDbType.NVarChar, 255).Value = $"%{token}%");` That allows you hint SQL Server which datatype of which size it's going to work with == small performance benefit. – Jaroslav Kadlec Feb 07 '17 at 14:29
  • Interesting idea. I have never thought about it. Thanks. – Alexei - check Codidact Feb 07 '17 at 15:40
-1

It is better practice to First assign Text box values to string variables then use them as below

String Firsttext = TextBox1.Text;
String SecondText = TextBox2.Text;

Then you can use it as follows

"SELECT * FROM customer WHERE FirstName LIKE '"+ Firsttext + "%" + "' OR LastName LIKE '" +SecondText + "%"+"'";
Jaroslav Kadlec
  • 2,505
  • 4
  • 32
  • 43
  • 1
    Watch out Ved this makes you very vulnerable to sql injection! – Thomas Feb 07 '17 at 12:35
  • With no offense I'd have doubts about being this good practice. It would be good practice to fully split Form logic from part where you're concatenating scripts. Then suggesting of using LIKE ...'"+Firsttext + '%'... is fundamentally wrong. At all this doesn't seem to be answer for original question. – Jaroslav Kadlec Feb 07 '17 at 14:25