How do I use the wildcard search parameter?

public DataTable Search()
{
    DataTable dt = new DataTable();
    SqlCommand searchcommand = new SqlCommand(
        "Select * from [ITEM MASTER] WHERE Item_Description LIKE  '%' @Item_Description  '%' ", con);

    searchcommand.Parameters.Add("@Item_Description", SqlDbType.NVarChar).Value = search;
    SqlDataAdapter da = new SqlDataAdapter(searchcommand);
    da.Fill(dt);
    return dt;
}

      

Here is my code. I need help creating a parameterized search using object oriented programming

+3


source to share


1 answer


Short answer

As Nathan said, just add +

on either side of the parameter @Item_Description

. This will merge it together with the rest of the command line.

SqlCommand searchcommand = new SqlCommand("Select * from [ITEM MASTER] WHERE Item_Description LIKE  '%' + @Item_Description + '%' ", con);

      

Additional Tips

If you want to make your code a little more readable you can use verbatim string@

to create . By the way, the verbatim line allows us to span a line across multiple lines, for example:



SqlCommand searchcommand = new SqlCommand(
     @"Select * 
       from [ITEM MASTER] 
       WHERE Item_Description 
       LIKE  '%' + @Item_Description + '%' ", con);

      

For more readability, you can put your string in your own variable, put T-SQL keywords in all caps, and add a semicolon at the end of the command text, which will look like this:

Final code example

var commandText = @"

SELECT * 
FROM [ITEM MASTER] 
WHERE Item_Description 
LIKE  '%' + @Item_Description + '%';

";

SqlCommand searchcommand = new SqlCommand(commandText, con);

      

This is much nicer to read, in my opinion, when you come across it in your maintenance job.

+2


source







All Articles